(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)

题目:2434. 使用机器人打印字典序最小的字符串



思路:贪心+栈,时间复杂度0(n)。
字符串t其实就是栈,后进先出。要让p的字典序最小,那当然是t每次弹出的字符,都小于或等于"剩下未入t里的字符串的字符",细节看注释。

C++版本:

cpp 复制代码
class Solution {
public:
    string robotWithString(string s) {
        int n=s.size();
        //预处理出后半段的最小字符
        vector<char> v(n+1);
        v[n]='z';
        for(int i=n-1;i>=0;i--){
            v[i]=min(v[i+1],s[i]);
        }
        // 答案
        string t="";
        // 栈,模拟t
        stack<char> st;
        // 遍历字符串s
        for(int i=0;i<n;i++){
        	// 当前字符入栈
            st.push(s[i]);
            // 当栈不为空,且栈顶字符<=后半段字符串s[i+1,n)中的所有字符
            while(st.size()>0 && st.top()<=v[i+1]){
            	// 出栈
                t.push_back(st.top());
                st.pop();
            }
        }
        return t;
    }
};

JAVA版本:

java 复制代码
class Solution {
    public String robotWithString(String s) {
        int n=s.length();
        char[] v=new char[n+1];
        v[n]='z';
        for(int i=n-1;i>=0;i--){
            v[i]=(char)Math.min(v[i+1],s.charAt(i));
        }
        StringBuilder ans=new StringBuilder();
        Deque<Character> st=new ArrayDeque<>();
        for(int i=0;i<n;i++){
            st.push(s.charAt(i));
            while(!st.isEmpty() && st.peek()<=v[i+1]){
                ans.append(st.pop());
            }
        }
        return ans.toString();
    }
}

Go版本:

go 复制代码
func robotWithString(s string) string {
    n:=len(s)
    v:=make([]byte,n+1)
    v[n]=byte('z')
    for i:=n-1;i>=0;i-- {
        v[i]=min(v[i+1],s[i]);
    }
    ans:=make([]byte,0,n)
    st:=make([]byte,n)
    top:=-1
    for i:=0;i<n;i++ {
        top++
        st[top]=s[i]
        for top>=0 && st[top]<=v[i+1] {
            ans=append(ans,st[top])
            top--
        }
    }
    return string(ans)
}
相关推荐
IUGEI3 分钟前
深入解析HTTP长连接原理
java·网络·后端·网络协议·tcp/ip·http·https
q***64975 分钟前
头歌答案--爬虫实战
java·前端·爬虫
凌波粒6 分钟前
SpringMVC基础教程(4)--Ajax/拦截器/文件上传和下载
java·前端·spring·ajax
汤姆yu16 分钟前
基于springboot的电脑商城系统
java·spring boot·后端
2501_9411114620 分钟前
C++与硬件交互编程
开发语言·c++·算法
未若君雅裁31 分钟前
LeetCode 51 - N皇后问题 详解笔记
java·数据结构·笔记·算法·leetcode·剪枝
失散131 小时前
架构师级别的电商项目——2 电商项目核心需求分析
java·分布式·微服务·架构·需求分析
Tim_101 小时前
【算法专题训练】30、二叉树的应用
算法
夜晚中的人海1 小时前
【C++】哈希表算法习题
c++·算法·散列表
水木姚姚1 小时前
初识C++
开发语言·c++