forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths1.cpp
More file actions
26 lines (26 loc) · 700 Bytes
/
Copy paths1.cpp
File metadata and controls
26 lines (26 loc) · 700 Bytes
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
// OJ: https://leetcode.com/problems/increasing-decreasing-string
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
string sortString(string s) {
int cnt[26] = {0};
for (char c : s) cnt[c - 'a']++;
int N = s.size();
string ans(N, '\0');
for (int i = 0; i < N; ) {
for (int j = 0; j < 26; ++j) {
if (!cnt[j]) continue;
ans[i++] = 'a' + j;
cnt[j]--;
}
for (int j = 25; j >= 0; --j) {
if (!cnt[j]) continue;
ans[i++] = 'a' + j;
cnt[j]--;
}
}
return ans;
}
};