Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both cases.
Example 1:
Input: s = "hello" Output: "holle"
Example 2:
Input: s = "leetcode" Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 105
s
consist of printable ASCII characters.
反转字符串中的元音字母。
思路基本同344题。不同之处在于344题要求不能使用额外空间,但是本题非得使用额外空间才能解决,不仅需要 hashset,也需要将 input 先转成数组才能判断。同时注意这道题的 testcase 是同时包含大写字母和小写字母的。
时间O(n)
空间O(n) - hashset
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {string} 4 */ 5 var reverseVowels = function (s) { 6 // corner case 7 if (s === null || s.length === 0) return ''; 8 9 // normal case 10 let res = s.split(''); 11 let vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); 12 let left = 0; 13 let right = s.length - 1; 14 while (left < right) { 15 while (left < right && !vowels.has(res[left])) { 16 left++; 17 } 18 while (left < right && !vowels.has(res[right])) { 19 right--; 20 } 21 let temp = res[left]; 22 res[left] = res[right]; 23 res[right] = temp; 24 left++; 25 right--; 26 } 27 return res.join(''); 28 };
Java实现
1 class Solution { 2 public String reverseVowels(String s) { 3 // corner case 4 if (s.length() == 0 || s == null) { 5 return s; 6 } 7 8 // normal case 9 String vowels = "aeiouAEIOU"; 10 int left = 0; 11 int right = s.length() - 1; 12 char[] words = s.toCharArray(); 13 while (left < right) { 14 while (left < right && vowels.indexOf(words[left]) == -1) { 15 left++; 16 } 17 while (left < right && vowels.indexOf(words[right]) == -1) { 18 right--; 19 } 20 21 // swap 22 char temp = words[left]; 23 words[left] = words[right]; 24 words[right] = temp; 25 left++; 26 right--; 27 } 28 return new String(words); 29 } 30 }
相关题目