Problem 345: Reverse Vowels of a String
思路
public class Solution {
public String reverseVowels(String s) {
HashSet<Character> hs = new HashSet<Character>();
hs.add('a');
hs.add('e');
hs.add('i');
hs.add('o');
hs.add('u');
hs.add('A');
hs.add('E');
hs.add('I');
hs.add('O');
hs.add('U');
int[] pos = new int[s.length()]; //record vowel character position
int count = 0; //record vowel number
for (int i = 0; i < s.length(); i++) {
if (hs.contains(s.charAt(i))) {
pos[count] = i;
count++;
}
}
char[] ans = s.toCharArray();
for (int i = 0; i < count; i++) {
ans[pos[i]] = s.charAt(pos[count - 1 - i]);
}
return String.valueOf(ans);
}
}易错点
Last updated