文章目录
反转字符串中的元音字母
题目描述
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello"
输出: "holle"
示例 2:
输入: "leetcode"
输出: "leotcede"
说明:
元音字母不包含字母"y"。
code
class Solution {
public String reverseVowels(String s) {
char[] sTmp = s.toCharArray();
char[] letter=new char[] {'a','e','i','o','u','A','E','I','O','U'}; //元音数组
//使用一个容器进行存储
Set<Character> set = new HashSet<Character>();
for (char c : letter) {
set.add(c);
}
int left = 0;
int right= s.length()-1;
while (left< right){
while (left < right && ! set.contains(sTmp[left])){
left++;
}
while (left <right && !set.contains(sTmp[right])){
right--;
}
//进行交换
if(left< right){
char tmp = sTmp[left];
sTmp[left] = sTmp[right];
sTmp[right] = tmp;
left++;
right--;
}
}
return String.valueOf(sTmp);
}
}