345. Reverse Vowels of a String - LeetCode
Question
345. Reverse Vowels of a String
Solution
思路:交换元音,第一次遍历,先把出现元音的索引位置记录下来,第二遍遍历元音的索引并替换。
Java实现:
public String reverseVowels(String s) {
List<Integer> store = new ArrayList<>();
char[] arr = s.toCharArray();
for (int i=0; i< arr.length; i++) {
switch (arr[i]) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
store.add(i);
break;
}
}
for (int i=0; i<store.size()/2; i++) {
int start = store.get(i);
int end = store.get(store.size() - 1 - i);
char tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
}
return String.valueOf(arr);
}