var sortString = function(s) { const num = newArray(26).fill(0); for (let ch of s) { num[ch.charCodeAt() - 'a'.charCodeAt()]++; }
let ret = ''; while (ret.length < s.length) { for (let i = 0; i < 26; i++) { if (num[i]) { ret += String.fromCharCode(i + 'a'.charCodeAt()); num[i]--; } } for (let i = 25; i >= 0; i--) { if (num[i]) { ret += String.fromCharCode(i + 'a'.charCodeAt()); num[i]--; } } } return ret; };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defsortString(self, s: str) -> str: num = [0] * 26 for ch in s: num[ord(ch) - ord('a')] += 1 ret = list() whilelen(ret) < len(s): for i inrange(26): if num[i]: ret.append(chr(i + ord('a'))) num[i] -= 1 for i inrange(25, -1, -1): if num[i]: ret.append(chr(i + ord('a'))) num[i] -= 1
funcsortString(s string)string { cnt := ['z' + 1]int{} for _, ch := range s { cnt[ch]++ } n := len(s) ans := make([]byte, 0, n) forlen(ans) < n { for i := byte('a'); i <= 'z'; i++ { if cnt[i] > 0 { ans = append(ans, i) cnt[i]-- } } for i := byte('z'); i >= 'a'; i-- { if cnt[i] > 0 { ans = append(ans, i) cnt[i]-- } } } returnstring(ans) }