The topic of dry
Write a function that takes a string as input and inverts the vowels in that string.
Example 1:
Input: "hello" Output: "holle"Copy the code
Solution:
The front pointer traverses backwards, and the back pointer traverses forwards. At the beginning of each loop, the corresponding values of the front and back Pointers are determined:
- If both are vowels, switch and move the pointer forward/back
- Determine whether the front and back Pointers are cause letters separately, if so, keep the current position of the pointer, if not, move forward/back
Code implementation:
Two-pointer implementation:
Execution time: 112 ms, beating 47.92% of all JavaScript submissions
Memory consumption: 42.8 MB, beating 96.04% of all JavaScript commits
var reverseVowels = function (s) {
let arrs = s.split(' ')
let arr = ['a'.'o'.'e'.'i'.'u'.'A'.'O'.'E'.'I'.'U']
let begin = 0, end = s.length - 1;
while (begin < end) {
if (arr.includes(s[begin]) && arr.includes(s[end])) {
// Convert the string to an array, replace the elements, and transfer the string
let temp = arrs[begin];
arrs[begin] = arrs[end];
arrs[end] = temp;
begin += 1;
end -= 1;
} else {
if (arr.includes(arrs[begin])) {
begin = begin
} else {
begin += 1
}
if (arr.includes(arrs[end])) {
end = end
} else {
end -= 1}}}return arrs.join(' ');
};
Copy the code