- 1370 上升下降字符串
- 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-decreasing-string - 给你一个字符串 s ,请你根据下面的算法重新构造字符串:
- 从 s 中选出 最小 的字符,将它 接在 结果字符串的后面。
从 s 剩余字符中选出 最小 的字符,且该字符比上一个添加的字符大,将它 接在 结果字符串后面。
重复步骤 2 ,直到你没法从 s 中选择字符。
从 s 中选出 最大 的字符,将它 接在 结果字符串的后面。
从 s 剩余字符中选出 最大 的字符,且该字符比上一个添加的字符小,将它 接在 结果字符串后面。
重复步骤 5 ,直到你没法从 s 中选择字符。
重复步骤 1 到 6 ,直到 s 中所有字符都已经被选过。
在任何一步中,如果最小或者最大字符不止一个 ,你可以选择其中任意一个,并将其添加到结果字符串。
请你返回将 s 中字符重新排序后的 结果字符串 。
解题思路:哈希表:记录各个字母出现的次数,正序遍历,反序遍历dic,每遍历一个字母加入result,且对应次数减一,直到所有字母次数都为0。
# python 3
class Solution:
def sortString(self, s: str) -> str:
dic = [0]*26
result = ''
count = 0
for ch in s:
dic[ord(ch) - ord('a')] +=1
while count<len(s):
for i in range(26):
if dic[i]>0:
result += chr(i +ord('a'))
count +=1
dic[i] -=1
if count >= len(s): return result
#range(start, end, step), [start, end)
for i in range(25, -1, -1):
if dic[i]>0:
result += chr(i+ord('a'))
count +=1
dic[i] -=1
if count >= len(s): return result
return result
class Solution {
public:
string sortString(string s) {
vector<int> dic(26,0);
string result;
for(char ch:s ){
//cout<<ch<<endl;
++dic[ch-'a'];
}
while (result.size()<s.size()){
for(int i=0; i<26;++i){
if(dic[i]>0){
--dic[i];
result.push_back(i+'a');
}
}
for (int i =25; i>=0; --i){
if(dic[i]>0){
--dic[i];
result.push_back(i+'a');
}
}
}
return result;
}
};