LeetCode394 Decode String java solution

题目链接:

https://leetcode.com/problems/decode-string/

点击打开链接

题目要求:

Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

这道题目要是用两个栈结构来进行计算,想了很长时间最后还是看的别人的答案

两个栈结构中,使用的时候要注意,存储数字的栈使用来来确定添加的次数的.每一次压栈都要注意压栈得时候应将上一个的栈中的数据清除.

public class Solution {
    public String decodeString(String s) {
        Stack<Integer> inStack = new Stack<>();
        Stack<StringBuffer> charStack = new Stack<>();
        StringBuffer sb = new StringBuffer();
        int count = 0;
        for(char c : s.toCharArray()) {
            if(Character.isDigit(c)) count = count * 10 + c - '0';
            else if(c == '[') {
                inStack.add(count);
                charStack.add(sb);
                count = 0;
                sb = new StringBuffer();
            }
            else if(c == ']') {
                StringBuffer tem = sb;
                sb = charStack.pop();
                for(int k = inStack.pop(); k > 0; k--) sb.append(tem);
            }
            else sb.append(c);
        }
        return sb.toString();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值