1370. 上升下降字符串 - 力扣(LeetCode)

题目有点难读懂,大体意思就是先升序再降序来回走,可以使用桶排序的思路:把不同的字母放在不同的桶里面,相同的字母放在同一个桶里面。假设桶为a--z,先从a桶出发,如果桶里面有元素,就取出一个(追加到res),一直走到z桶,此时又从z桶出发,向a桶的方向走,如此来回反复即可。
class Solution {
public:
int count[26];
string sortString(string s) {
for(const auto &c : s) ++count[c-'a'];//桶排序的思路(计数)
string res;
while(res.size() < s.size()){
for(int i = 0; i < 26; ++i){//升序走一遍
if(count[i] > 0){
res += i+'a';
--count[i];
}
}
for(int i = 25; i >= 0; --i){//降序走一遍
if(count[i] > 0){
res += i+'a';
--count[i];
}
}
}
return res;
}
};
也可以原地操作:
class Solution {
public:
int count[26];
string sortString(string s) {
for(const auto &c : s) ++count[c-'a'];//桶排序的思路(计数)
int cnt = 0;
while(cnt < s.size()){
for(int i = 0; i < 26; ++i){//升序走一遍
if(count[i] > 0){
s[cnt++] = i+'a';
--count[i];
}
}
for(int i = 25; i >= 0; --i){//降序走一遍
if(count[i] > 0){
s[cnt++] = i+'a';
--count[i];
}
}
}
return s;
}
};
博客围绕LeetCode 1370题展开,该题题意较难理解,主要是先升序再降序操作。解题可采用桶排序思路,将不同字母放不同桶,相同字母放同一桶,按顺序从桶中取元素追加到结果;还可进行原地操作。
617

被折叠的 条评论
为什么被折叠?



