Reverse Vowels of a String

本文介绍了一种使用双指针技巧反转字符串中元音字母的方法,并提供了详细的JavaScript实现步骤。通过该方法,可以在不改变字符串中辅音位置的情况下,仅交换元音字母的位置。

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值