JAVASCRIPT Leetcode1370. Increasing Decreasing String

1370 Increasing Decreasing String

题目
Given a string s. You should re-order the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.

Return the result string after sorting s with this algorithm.

关键词:sort,string
思路

  1. 建立数组,以(小写字符code-97)为元素,计算其出现次数。
  2. 建立res字符串,当字符串长度达到输入字符串长度,则停止。
  3. 第一轮循环是根据递增数组,发现元素,加入res,次数减一。
  4. 第二轮循环是根据递减数组,发现数组加入res,次数减一。
  5. 两轮循环结束,检查2step。

时间复杂度:O(n). 空间是O(26)
解题

var sortString = function (s) {
    let arr = new Array(26).fill(0); //arr[charcode diff] = freq
    let res = "";
    // //store freq
    for (let i = 0; i < s.length; i++) {
        arr[s.charCodeAt(i) - 97] += 1;
    }

    //traverse get all increase, then get all decrease
    while (res.length < s.length) {
        for (let i = 0; i < 26; i++) {
            if (arr[i] != 0) { //here has char
                res += (String.fromCharCode(i + 97));
                arr[i]--;
            }
        }
        for (let i = 25; i >= 0; i--) {
            if (arr[i] != 0) {
                res += (String.fromCharCode(i + 97));
                arr[i]--;
            }
        }
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值