[To review] Leetcode 394: Decode String

Description:

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".


Solution:

本题主要练习栈的应用,在这里,新建了两个栈,一个栈用来存系数,另一个栈用来存字符,当遇到数字,则进第一个栈,当遇到字符,则进第二个栈,当遇到],则字符串出栈且循环第一个栈栈顶数字次。

class Solution {
    public static String decodeString(String s) {
	        String res = "";
	        Stack<Integer> countStack = new Stack<>(); //存储数字的栈
	        Stack<String> resStack = new Stack<>();  //存储字符的栈
	        int idx = 0;
	        while (idx < s.length()) {
	        	//字符串中数字部分
	            if (Character.isDigit(s.charAt(idx))) {
	                int count = 0;
	                //对于有多位数字,例123=((1*10)+2)*10+3
	                while (Character.isDigit(s.charAt(idx))) {
	                    count = 10 * count + (s.charAt(idx) - '0');
	                    idx++;
	                }
	                //进存储数据的栈
	                countStack.push(count);
	            }
	            //字符串中[
	            else if (s.charAt(idx) == '[') {
	                resStack.push(res); //进存储字符的栈,进空
	                res = "";
	                idx++;
	            }
	            //字符串中]
	            else if (s.charAt(idx) == ']') {
	            	//新建StringBuilder,方便插入数据
	                StringBuilder temp = new StringBuilder (resStack.pop());
	                //系数输出(重复次数)
	                int repeatTimes = countStack.pop();
	                for (int i = 0; i < repeatTimes; i++) {
	                    temp.append(res);
	                }
	                res = temp.toString();
	                idx++;
	            }
	            //字符串中的字符
	            else {
	                res += s.charAt(idx++); //连接字符
	            }
	        }
	        return res;
	    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值