您的位置:首页 > 其它

【Leetcode】Reverse Vowels of a String

2016-05-27 23:46 323 查看
题目链接:https://leetcode.com/problems/reverse-vowels-of-a-string/

题目:

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".

思路:

easy

算法

public String reverseVowels(String s) {
char c[] = s.toCharArray();
Set<String> vowels = new HashSet<String>();
vowels.add("a");
vowels.add("e");
vowels.add("i");
vowels.add("o");
vowels.add("u");
vowels.add("A");
vowels.add("E");
vowels.add("I");
vowels.add("O");
vowels.add("U");
int v1=-1,v2=-1;
for(int start=0,end=c.length-1;start<end;){
if(v1==-1){
if(vowels.contains(c[start]+""))
v1 = start;
else
start++;
}
if(v2==-1){
if(vowels.contains(c[end]+""))
v2 = end;
else
end--;
}

if(v1!=-1&&v2!=-1){
char tmp = c[v1];
c[v1] = c[v2];
c[v2] = tmp;
v1 = -1;
v2 = -1;
start++;
end--;
}

}

return new String(c);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: