头像

带翅膀的猫

时光荏苒,我们一直都在

《LeetCode刷题(Easy Rank):824. Goat Latin》

 3月前  •   LeetCode  •     •   33  •   0

Question:

A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

  • If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word.
    For example, the word ‘apple’ becomes ‘applema’.
  • If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma".
    For example, the word "goat" becomes "oatgma".
  • Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
    For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.

Return the final sentence representing the conversion from S to Goat Latin.

Example 1:

示例Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

示例Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Solution:

JAVAclass Solution {
 public String toGoatLatin(String S) {
    	String[] resultArr = new String[S.length()];
    	int resultArrSize = 0;
        char[] arr = new char[1000];
        int arrSize = 0;
        
        int startIndex = 0;
        int count = 1;
        for(int i = 0; i < S.length(); i++) {
        	arrSize = 0;
        	while(i < S.length()&& S.charAt(i) != ' ') {
        		++i;
        	}
        	if(isVowel(S.charAt(startIndex))) {
        		for(int j = startIndex; j < i; j++) {
        			arr[arrSize++] = S.charAt(j);  
        		}
        	}else {
        		for(int j = startIndex+1; j < i; j++) {
        			arr[arrSize++] = S.charAt(j);
        		}
        		arr[arrSize++] = S.charAt(startIndex);
        	}
        	arr[arrSize++] = 'm';
    		arr[arrSize++] = 'a';
        	for(int j = i+2; j < i+2+count; j++) {
    			arr[arrSize++] = 'a';
    		}
    		resultArr[resultArrSize++] = new String(arr, 0, arrSize);
        	startIndex = i+1;
        	++count;
        }
        
        StringBuilder result = new StringBuilder();
        for(int i = 0; i < resultArrSize; i++) {
        	result.append(resultArr[i]);
        	if(i != resultArrSize-1) {
        		result.append(' ');
        	}
        }
        return result.toString();
    }
    
    public boolean isVowel(char c) {
    	c = Character.toLowerCase(c);
    	return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }
}

 

 

上一篇:
下一篇:

 评论


 已有0条评论

    还没有任何评论,你来说两句吧!