【力扣】1370. 上升下降字符串 ---- 哈希表

  • 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值