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”
Note:
The vowels does not include the letter “y”.
解法
用双指针的头尾指针方法,一个指针从头开始遍历,一个指针从末尾开始遍历直到两个指针遇见则遍历完。这个题还要处理的是一开始将string转成list,因为string不能赋值,最后再用"’’.join(s)转回string
python
class Solution:
def reverseVowels(self, s: str) -> str:
i=0
s=list(s)
j=len(s)-1
vowel=set(list('aieouAEIOU'))
while(i<j):
if(s[i] in vowel and s[j] in vowel):
s[i],s[j]=s[j],s[i]
i=i+1
j=j-1
if(s[i] not in vowel):
i=i+1
if(s[j] not in vowel):
j=j-1
return ''.join(s)
java
需要用到java string 的contains方法,需要把string转换为charArray
class Solution {
public String reverseVowels(String s) {
int i=0,j=s.length()-1;
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
while(i<j){
if(vowels.contains(chars[i]+"")&&vowels.contains(chars[j]+"")){
char tmp=chars[i];
chars[i]=chars[j];
chars[j]=tmp;
i++;
j--;
}
else if(!vowels.contains(chars[i]+"")){
i++;
}
else if(!vowels.contains(chars[j]+"")){
j--;
}
}
return new String(chars);
}
}