上升下降字符
题目: 给你一个字符串 s ,请你根据下面的算法重新构造字符串:
从 s 中选出 最小 的字符,将它 接在 结果字符串的后面。 从 s 剩余字符中选出 最小 的字符,且该字符比上一个添加的字符大,将它 接在 结果字符串后面。 重复步骤 2 ,直到你没法从 s 中选择字符。 从 s 中选出 最大 的字符,将它 接在 结果字符串的后面。 从 s 剩余字符中选出 最大 的字符,且该字符比上一个添加的字符小,将它 接在 结果字符串后面。 重复步骤 5 ,直到你没法从 s 中选择字符。 重复步骤 1 到 6 ,直到 s 中所有字符都已经被选过。 在任何一步中,如果最小或者最大字符不止一个 ,你可以选择其中任意一个,并将其添加到结果字符串。
请你返回将 s 中字符重新排序后的 结果字符串 。
来源:力扣(LeetCode) leetcode-1370.上升下降字符串
题解:
- 对字符串按大小进行分割,因为是有限字符采用固定数组进行填充
- 从前到后依次填充,从后往前依次填充。重复该步骤
/**
* @param {string} s
* @return {string}
*/
var sortString = function(s) {
let num = new Array(26).fill(0), codeA = 'a'.charCodeAt(0);
for(let i = 0; i < s.length; i++) {
num[s[i].charCodeAt(0) - codeA]++;
}
let dir = 1, result = [], index = 0;
while(result.length < s.length) {
if(num[index] > 0) {
result.push(index);
num[index]--;
}
if (dir == 1) {
++index && index >= num.length && ( dir = -dir) && (index = num.length - 1);
}else if(dir == -1){
--index && index < 0 && ( dir = -dir) && (index = 0);
}
}
return result.reduce((res, value) => {
res += String.fromCharCode(value + codeA);
return res;
},'');
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
上次更新: 2025/09/05, 8:09:00