345. Reverse Vowels of a String
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" // correct May use a HashSet to reduce the look up time to O(1) public class Solution { public String reverseVowels(String s) { if(s == null || s.length()==0) return s; String vowels = "aeiouAEIOU"; char[] chars = s.toCharArray(); int start = 0; int end = s.length()-1; while(start<end){ while(start<end && !vowels.contains(chars[start]+"")){ start++; } while(start<end && !vowels.contains(chars[end]+"")){ end--; } char temp = chars[start]; chars[start] = chars[end]; chars[end] = temp; start++; end--; } return new String(chars); } // compile error class Solution { public String reverseVowels(String s) { HashSet<Character> set = new HashSet<>(){'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; char[] word = s.toCharArray(); int i = 0; int j = s.length() - 1; while( i < j){ while( i < j && !set.contains(word[i])){ i++; } while( i < j && !set.contains(word[j])){ j--; } char tmp = word[i]; word[i] = word[j]; word[j] = tmp; i++; j--; } return new String(word); } }
posted on 2018-11-08 15:46 猪猪🐷 阅读(122) 评论(0) 收藏 举报
浙公网安备 33010602011771号