上升下降字符串

LeetCode每日一题,1370. Increasing Decreasing String

先看题目描述

DdtvPx.png

大意就是给定一个字符串 s,让我们根据给定的算法重构字符串,并让我们返回重构后的字符串

算法和思路

基本思路就是维护一个长度为 26 的频次数组 count 记录下字符串中所有字母出现的次数,并用 max 记录下字符串中某字母重复出现的最大次数。然后按照先顺序再逆序的顺序遍历 count 数组,每当遍历到一个 count[j] > 0 时,就将其对应字母添加到结果字符串 res 后面,并将 count[j] - 1,遍历 count 数组的次数达到 max 后,将 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
27
28
29
class Solution {
public String sortString(String s) {
StringBuilder res = new StringBuilder();
int[] count = new int[26];
int max = 0;
for (char c : s.toCharArray()) {
count[c - 'a']++;
max = Math.max(max, count[c - 'a']);
}
for (int i = 0; i < max; i++) {
if (i % 2 == 0) {
for (int j = 0; j < 26; j++) {
if (count[j] > 0) {
res.append((char)('a' + j));
count[j]--;
}
}
} else {
for (int j = 25; j >= 0; j--) {
if (count[j] > 0) {
res.append((char)('a' + j));
count[j]--;
}
}
}
}
return res.toString();
}
}