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, e, i, o, u. 字母y是半元音,题中已经申明元音字母不包括y.
思路:用两个标志位left和right,分别从数组的两端开始判断当前字母是否为元音,如果两边字母同时都是元音字母,则交换;如果左边字母不是元音,则左边标志位left加1;如果右边字母不是元音,则右边标志位right加1。另:要考虑字母的大小写
解法一:用String类的contains(CharSequence s)方法,代码如下:
public String reverseVowels(String s){ if(s == null || s.length() == 0) return s; char[] chars = s.toCharArray(); int left = 0, right = chars.length - 1; String str = "aeiou"; char ch; boolean lFlag, rFlag; while(left < right){ lFlag = str.contains(String.valueOf(chars[left]).toLowerCase()); rFlag = str.contains(String.valueOf(chars[right]).toLowerCase()); if(!lFlag) left++; else if(!rFlag) right--; else if(lFlag && rFlag){ ch = chars[right]; chars[right] = chars[left]; chars[left] = ch; left++; right--; } } return String.valueOf(chars); }
解法二:利用自定义的函数判断字母是否为元音
点评:运行时间比上一个方法更短
public String reverseVowels(String s){ if(s == null || s.length() == 0) return s; char[] chars = s.toCharArray(); int left = 0, right = chars.length - 1; char ch; boolean lFlag, rFlag; while(left < right){ lFlag = isVowels(Character.toLowerCase(chars[left])); rFlag = isVowels(Character.toLowerCase(chars[right])); if(!lFlag) left++; else if(!rFlag) right--; else if(lFlag && rFlag){ ch = chars[right]; chars[right] = chars[left]; chars[left] = ch; left++; right--; } } return String.valueOf(chars); } public boolean isVowels(char ch){ if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; else return false; }