Reverse Vowels of a String

来源:互联网 发布:阿里云邮箱企业版登录 编辑:程序博客网 时间:2024/06/09 04:55

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('');};


0 0
原创粉丝点击