1. 题目描述
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”.
2. 解题思路
题目为字符串交换的变种题目,交换一个字符串中的所有元音字母(a,e,i,o,u),解题思路为设置一前一后两个指针,一个从前往后扫找到第一个元音字母,一个从后往前扫找到倒数第一个元音字母,交换两个字母,字符串一共扫描一遍,时间复杂度O(N)。需要注意的是,元音字母一开始我只考虑到了小写的aeiou,没有考虑到大写的。且需要仔细考虑交换时start和end的条件,避免越界。
3. Code
/**
* Created by ritaliu on 16/6/25.
*/
public class Solution {
/**
* 思路:两个指针一个往前扫一个往后扫,进行交换
* @param s
* @return
*/
public String reverseVowels(String s) {
int start = 0, end = s.length() - 1;
StringBuffer sb = new StringBuffer(s);
while (start < end) {
while(!isVowel(s.charAt(start)) && start < end)
{
++start;
}
while(!isVowel(s.charAt(end)) && end > start)
{
--end;
}
if (start < end){
// 交换两个字母
sb.setCharAt(start, s.charAt(end));
sb.setCharAt(end, s.charAt(start));
++start;
--end;
}
}
return sb.toString();
}
/**
* 检查一个字母是否为一个元音字母
* @param c
* @return
*/
public boolean isVowel(char c) {
String s = "aAeEiIoOuU";
if (s.contains(String.valueOf(c)))
return true;
return false;
}
}