题目:
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
解题思路:
使用双指针指向待反转的字符,一个指针从头向尾遍历,另外一个指针从尾向头遍历。当两个指针指向的字符都是元音字符时,交换两个指针所指的字符。若其中只有一个指针指向的字符是元音字符时,将相应指针加1/减1,另外指针不变。代码如下:
package Leetcode_Github;
import java.util.Arrays;
import java.util.HashSet;
public class TwoPoints_ReverseVowels_345_1101 {
public String ReverseVowels(String s){
//判空
if (s == null || s.length() == 0) {
return s;
}
//存放返回结果
char[] result = new char[s.length()];
//将元音字母存入set中
HashSet<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
int i = 0;
int j = s.length()-1;
while (i <= j) {
char ci = s.charAt(i);
char cj = s.charAt(j);
if (!vowels.contains(ci)) {
result[i++] = ci; //ci不是元音字母,i++
} else if (!vowels.contains(cj)) {
result[j--] = cj; //cj不是元音字母,j--
}
else {
//ci 和cj都是元音字母,进行交换
result[i++] = cj;
result[j--] = ci;
}
}
return new String(result); //将数组转换成字符串返回
}
}