(Js) Leetcode 345. Reverse vowels in a string

topic:

Write a function that takes a string as input and reverses the vowels in the string.

Example 1:

Input: "hello"
Output: "holle"
Example 2:

Input: "leetcode"
Output: "leotcede"

prompt:

Vowels do not contain the letter "y".

Ideas:

Use dual pointers

Code:

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
    let arr = ['a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U'];
    s = s.split('');
    let i = 0, j = s.length - 1;
    while(i < j) {
        if(arr.indexOf(s[j]) == -1) {
            j--;
            continue;
        }
        if(arr.indexOf(s[i]) == -1) {
            i++;
            continue;
        }

        [s[i], s[j]] = [s[j], s[i]];
        i++;
        j--
    }
    return s.join('');
};

operation result:

 

Guess you like

Origin blog.csdn.net/M_Eve/article/details/112974322