LeetCode 6202. 使用机器人打印字典序最小的字符串

这个题是个模拟题,使用堆栈来表示字符串t


对于s和t有以下几种情况:

  • 当字符串 t 为空时,寻找 s 字符串中最小的字符 s[j] 并将s[j]之前的字符放入t中,s[j] 放入结果p中
  • 当 t 不为空时,当字符串 s 中最小的字符 s[j] 小于 t 尾部的字符时,将剩余的s字符串中 s[j]之前的字符放入t,s[j] 放入结果p
  • 当 t 不为空时,当字符串 s 中最小的字符 s[j] 大于 t 尾部的字符时,将t尾部字符放入结果p
    *当t 不为空,s 为空时,将 t 放入结果p

这个题的难点之一就是如何快速找到s中最小的字符s[j],使用暴力搜索会超时,这里使用map和queue来存储字符的位置,从a到z寻找,当出现第一个满足要求的位置时,此时s[j] 一定是最小的字符


class Solution {
public:
    unordered_map<char,queue<int>> map;
    // 找到s中最小字符s[j]
    int findMin(int p)
    {
        int res = p;
        for (int i = 0; i < 26; i++)
        {
            if (map['a' + i].empty())
                continue;
            while (!map['a' + i].empty())
            {
                if (map['a' + i].front() >= p)
                {
                    res = map['a' + i].front();
                    // map['a' + i].pop();
                    return res;
                }
                map['a' + i].pop();
            }
        }
        return res;
    }
    string robotWithString(string s) {
        
        for(int i = 0; i < s.size(); i++)
        {
            map[s[i]].push(i);
        }
        string p = "";
        stack<char> t;
        int i = 0;
        int j = 0;
        while(i < s.size())
        {
            j = findMin(i);		//s[j]为此时s中最小的字符
            if(t.empty() || t.top() > s[j])
            {
            	//将s[j]之前的字符放入t
                while(i < j)
                    t.push(s[i++]);
                p += s[i];	//s[j] 放入p
                i++;
            }
            else
            {
            	// s[j] 大于 t尾部字符,将t尾部字符放入p
                p += t.top();
                t.pop();
            }
            
        }
        while(!t.empty())
        {
            p += t.top();
            t.pop();
        }
        return p;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值