p345

LeetCode p345 Reverse Vowels of a String 题解

1.题目:

Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = “hello”, return “holle”.
Example 2:
Given s = “leetcode”, return “leotcede”.
Note:
The vowels does not include the letter “y”.

题意:

输入一个字符串,将第一个元音字母与最后一个元音字母交换,第二个与倒数第二个交换。。以此类推。

2.解题思路:

两个指针搜索交换。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
public class Solution {
public String reverseVowels(String s) {
char[] a = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
char[] list = s.toCharArray();

HashSet<Character> characters = new HashSet<Character>();
for (char i : a) {
characters.add(i);
}

for (int i = 0, j = list.length - 1; i < j; i++, j--) {
while (i < j && (!characters.contains(list[i]))) {
i++;
}
while (i < j && (!characters.contains(list[j]))) {
j--;
}
// System.out.println(i+" "+j);
if (i >= j)
break;
char c = list[i];
list[i] = list[j];
list[j] = c;
// System.out.println(new String(list));
}
return new String(list);
}
}


4.一些总结: