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
思路:
- 建立数组,以(小写字符code-97)为元素,计算其出现次数。
- 建立res字符串,当字符串长度达到输入字符串长度,则停止。
- 第一轮循环是根据递增数组,发现元素,加入res,次数减一。
- 第二轮循环是根据递减数组,发现数组加入res,次数减一。
- 两轮循环结束,检查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;
}