Created
February 10, 2020 08:13
-
-
Save yitonghe00/4ba5b8c28af1b7c877781ce2ca9eb52f to your computer and use it in GitHub Desktop.
824. Goat Latin (https://leetcode.com/problems/goat-latin/): 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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// String solution | |
// Time: O(L + N ^ 2) where L = S.length() and N = words.length, 2ms | |
// Space: O(L + N ^ 2), 38.3mb | |
class Solution { | |
public String toGoatLatin(String S) { | |
Set<Character> vowel = new HashSet<>(); | |
for(char c : "aeiouAEIOU".toCharArray()) vowel.add(c); | |
StringBuilder ans = new StringBuilder(); | |
String ending = "a"; | |
for(String word : S.split(" ")) { | |
char first = word.charAt(0); | |
if(vowel.contains(first)) { | |
ans.append(word); | |
} else { | |
ans.append(word.substring(1, word.length())); | |
ans.append(first); | |
} | |
ans.append("ma" + ending + " "); | |
ending += "a"; | |
} | |
ans.deleteCharAt(ans.length() - 1); | |
return ans.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment