LeetcodeReverse Vowels of a String
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeReverse Vowels of a String相关的知识,希望对你有一定的参考价值。
题目链接: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);
}
以上是关于LeetcodeReverse Vowels of a String的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Reverse Vowels of a String
LeetCode #345 Reverse Vowels of a String
[LeetCode]345 Reverse Vowels of a String
LeetCode 345. Reverse Vowels of a String