[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;
	    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41876155/article/details/80070248
今日推荐