题目:
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".
链接:
https://leetcode.com/problems/reverse-vowels-of-a-string/?tab=Description
3/12/2017
注意的问题:
1. 大小写都要包括
2. 第10, 11行需要是while不是if,而且要check start/end的合法性
1 public class Solution { 2 public String reverseVowels(String s) { 3 if (s.length() < 2) return s; 4 5 StringBuilder sb = new StringBuilder(s); 6 int start = 0, end = sb.length() - 1; 7 HashSet<Character> h = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); 8 9 while (start < end) { 10 while (!h.contains(sb.charAt(start)) && start < end) start++; 11 while (!h.contains(sb.charAt(end)) && start < end) end--; 12 if (start < end) { 13 char tmp = sb.charAt(start); 14 sb.setCharAt(start, sb.charAt(end)); 15 sb.setCharAt(end, tmp); 16 start++; 17 end--; 18 } 19 } 20 return sb.toString(); 21 } 22 }