1370. 上升下降字符串

 

思路:即先拼接string的升序序列,再拼接其降序序列。
1、将string转成list;
2、升序排list,各元素取一个拼接到res,将拼接过的元素从原list中删除;
3、降序排list,各元素取一个拼接到res,将拼接过的元素从原list中删除;
4、重复2和3,直到list为空。
若最小或者最大字符不止一个 ,只选其中任意一个拼接到结果字符串。
 1 class Solution(object):
 2     def sortString(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         # 返回值
 8         res = ""
 9         # 转成list
10         lists = list(s)
11         # 直到原串为空,结束循环
12         while len(lists) > 0:
13             # 升序排列
14             lists.sort(reverse=False)
15             # 遍历前先清空
16             temp = ""
17             for i, ch in enumerate(lists):
18                 if ch not in temp:
19                     temp += ch
20             # 拼接结果
21             res += temp
22             # 将拼接过的字符从原list中删掉
23             for i in range(len(temp)):
24                 lists.remove(temp[i])
25 
26             # 降序排列
27             lists.sort(reverse=True)
28             # 清空记录
29             temp = ""
30             for i, ch in enumerate(lists):
31                 if ch not in temp:
32                     temp += ch
33             # 拼接结果
34             res += temp
35             # 将拼接过的字符从原list中删掉
36             for i in range(len(temp)):
37                 lists.remove(temp[i])
38         return res
39 
40 
41 if __name__ == '__main__':
42     solution = Solution()
43     print(solution.sortString(s="bbbbccccaaaa"))
 
原文地址:https://www.cnblogs.com/panweiwei/p/12712846.html