[LeetCode][JavaScript][Python]Reverse Vowels of a String
Reverse Vowels of a String
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".
https://leetcode.com/problems/reverse-vowels-of-a-string/
将字符串中的元音倒序排列,英语中元音为a, e, i, o, u,包含大小写。
双指针,一个在头一个在尾,找了元音就交换两个指针指向的内容。
最近在学python,之后会尽量用python。
Javascript:
1 /** 2 * @param {string} s 3 * @return {string} 4 */ 5 var reverseVowels = function(s) { 6 var i, res = s.split(''), start = 0, end = s.length - 1, 7 aVowels = ['a', 'e', 'i', 'o', 'u']; 8 while(start < end){ 9 while(start < end && !isVowel(s[start])) 10 start++; 11 while(start < end && !isVowel(s[end])) 12 end--; 13 if(start !== end) 14 swap(start, end); 15 start++; 16 end--; 17 } 18 return res.join(''); 19 20 function isVowel(char){ 21 if(aVowels.indexOf(char.toLowerCase()) !== -1){ 22 return true; 23 } 24 return false; 25 } 26 function swap(i, j){ 27 var temp = res[i]; 28 res[i] = res[j]; 29 res[j] = temp; 30 } 31 };
Python:
1 class Solution(object): 2 def reverseVowels(self, s): 3 res = list(s) 4 vowels = ['a', 'e', 'i', 'o', 'u'] 5 start = 0; end = len(s) - 1 6 while start < end: 7 while start < end and (s[start].lower() not in vowels): 8 start += 1 9 while start < end and (s[end].lower() not in vowels): 10 end -= 1 11 if(start != end): 12 tmp = res[start] 13 res[start] = res[end] 14 res[end] = tmp 15 start += 1; end -= 1 16 return ''.join(res)