算法day25

第一题

394. 字符串解码

解法:模拟栈的完成上述的操作;

分析:

下面以如图的字符串来分析;

首先定义一个数字栈用来存放数字,同时定义一个容器stringbuffer栈,里面用来存放字符串;

1、遇到数字:将这个数字进栈操作到数字栈中;

2、遇到'【'符号,将【符号后面的字符串提取出来,放入到字符串栈中;

3、遇到'】':首先将此时字符串栈顶的字符串拿出来,进行解析,根据数字栈栈顶的数字来重复刚取出来的字符串,最后将解析好的字符串放在字符串栈顶;

4、遇到单独的字符:将这个单独的字符串直接放在字符串栈顶字符的后面;

小细节:如果遇到的数字是非单位数,我们要能够完整的获取到这个多位数的数字;

综上所述,代码如下:

java 复制代码
class Solution {
    public String decodeString(String s) {
        Stack<StringBuffer> st = new Stack<>();
        st.push(new StringBuffer());//先放一个空串
        Stack<Integer> nums = new Stack<>();
        int i = 0,n = s.length();
        char[] s1 = s.toCharArray();
        while(i < n){
            //遇到数字
            if(s1[i] >= '0' && s1[i] <= '9' ){
                int tmp = 0;
                while(i < n && s1[i] >= '0' && s1[i] <= '9' ){
                    tmp = tmp * 10 + (s1[i] - '0');
                    i++;
                }
                nums.push(tmp);
            }
            else if(s1[i] == '['){
                i++;//把后面的字符串提取出来
                StringBuffer tmp = new StringBuffer();
                while(i < n && s1[i] >= 'a' && s1[i] <= 'z' ){
                    tmp.append(s1[i]);
                    i++;
                }
                st.push(tmp);
            }
            else if(s1[i] == ']'){
                //解析字符串
                StringBuffer tmp = st.pop();
                int num = nums.pop();
                while(num-- != 0){
                   st.peek().append(tmp);
                }
                i++;
            }
            else{
                StringBuffer tmp = new StringBuffer();
                while(i < n && s1[i] >= 'a' && s1[i] <= 'z' ){
                    tmp.append(s1[i]);
                    i++;
                }
                st.peek().append(tmp);
            }

        }
        return st.peek().toString();
    }
}

第二题

解法:模拟栈的基本运行逻辑

步骤:

1、让元素一直进栈操作

2、定义指针来指向popped数组的0号位置元素,在进栈后判断栈顶元素是否和出栈元素的指针所指的元素相同,如果相同,则进行出栈操作;如果不同则指针位置向后移动一个位置,接着进行入栈操作;

综上所述,代码如下:

java 复制代码
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> st = new Stack<>();
        int i = 0,n = popped.length;
        for(int x : pushed){
            st.push(x);
            while(!st.isEmpty() && st.peek() == popped[i]){
                st.pop();
                i++;
            }
        }
        return i == n;
    }
}

ps:本次的内容就到这里了,如果对你有所帮助的话,就请一键三连哦!!!

相关推荐
NAGNIP18 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队19 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 天前
大模型微调框架之LLaMA Factory
算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客1 天前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法