1 class Solution: 2 def sortString(self, s: str) -> str: 3 n = len(s) 4 dic = {} 5 for i in range(n): 6 if s[i] not in dic: 7 dic[s[i]] = 1 8 else: 9 dic[s[i]] += 1 10 sorted_dic1 = sorted(dic.items(),key=lambda x:(x[0])) 11 sorted_dic2 = sorted(dic.items(),key=lambda x:(x[0]),reverse=True) 12 count = 0 13 result = '' 14 while count < n: 15 for d in sorted_dic1: 16 key = d[0] 17 if dic[key] > 0: 18 dic[key] -= 1 19 result += key 20 count += 1 21 for d in sorted_dic2: 22 key = d[0] 23 if dic[key] > 0: 24 dic[key] -= 1 25 result += key 26 count += 1 27 return result
Algorithm thinking: hash.
Use a dictionary record the number of times each character appears on the dictionary sort twice.
According to the sort of positive sequence of characters, the characters sorted in reverse order.
A "snake" cycle, the first positive sequence traversing the dictionary, each character removed from a splice to result string; then traverse the dictionary in reverse order, each time removed from a character string splicing to result.
When the number n of the splice, a description of all characters have been spliced to the result string and returns the result string.