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".
Tags
Two Pointers, String
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Two pointers starting from each side of the string.
Loop to get the vowels and swap them.
*** One thing needs to pay attention is, String is irreplaceable. We need to transform to array and update the value and toString() back.
/**
* @param {string} s
* @return {string}
*/
var reverseVowels = function (s) {
var len = s.length;
var start = 0, end = len - 1;
var vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
var sarray = s.split('');
while (start < end) {
while (start < len && vowels.indexOf(sarray[start]) === -1) {
start++;
}
while (end >= 0 && vowels.indexOf(sarray[end]) === -1) {
end--;
}
if (start < end) {
var temp = sarray[end];
sarray[end] = sarray[start];
sarray[start] = temp;
start++;
end--;
}
}
return sarray.join('');
};