(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)
}
相关推荐
朦胧之5 小时前
AI 编程-老项目改造篇
java·前端·后端
kisshyshy10 小时前
🍦 雪糕、食堂、火车厢:三幅漫画吃透栈、队列与链表
javascript·算法
程序猿大帅10 小时前
别再只当调包侠了:用 Spring AI 落地 Function Calling,我被大模型硬生生砸出了三个大坑
java
Bolt11 小时前
TypeScript 7.0 来了:当 tsc 用 Go 重写之后
javascript·typescript·go
程序员晓琪11 小时前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly11 小时前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
众少成多积小致巨11 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
东坡白菜11 小时前
破局全栈:前端开发的Java入门实战记录—JPA(2)
java·后端
Go_error14 小时前
Datatypes:Go 轻松支持数据库JSON类型
后端·go
猿人谷17 小时前
不只是 CPU 阈值:STAR 如何用 GAT + Transformer 做容器级自动扩缩容?
人工智能·算法