Q:
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".
Note:
The vowels does not include the letter "y".
A:
就是两个指针互相交换
public class Solution {
public String reverseVowels(String s) {
StringBuffer buf = new StringBuffer(s);
int i =0, j = buf.length()-1;
Set<Character> set = new HashSet<>();
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
set.add('A');
set.add('E');
set.add('I');
set.add('O');
set.add('U');
while(i<j){
while(i<j && set.contains(buf.charAt(i))==false)
i++;
while(i<j && set.contains(buf.charAt(j))==false)
j--;
if(i<j){
char ch = buf.charAt(i);
buf.setCharAt(i,buf.charAt(j));
buf.setCharAt(j,ch);
i++;
j--;
}
}
return buf.toString();
}
}
Errors:
忘了考虑大写字母的情况Given s = "hello", return "holle".
Given s = "leetcode", return "leotcede".
The vowels does not include the letter "y".
public class Solution {
public String reverseVowels(String s) {
StringBuffer buf = new StringBuffer(s);
int i =0, j = buf.length()-1;
Set<Character> set = new HashSet<>();
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
set.add('A');
set.add('E');
set.add('I');
set.add('O');
set.add('U');
while(i<j){
while(i<j && set.contains(buf.charAt(i))==false)
i++;
while(i<j && set.contains(buf.charAt(j))==false)
j--;
if(i<j){
char ch = buf.charAt(i);
buf.setCharAt(i,buf.charAt(j));
buf.setCharAt(j,ch);
i++;
j--;
}
}
return buf.toString();
}
}
No comments:
Post a Comment