394. Decode String

来源:互联网 发布:分形设计软件 编辑:程序博客网 时间:2024/06/06 10:17

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


这种和括号相关的题目,一般都可以用stack来做。创建两个stack,一个存储integer,另一个存储单个字符串元素。同时需要注意括号前的数字有可能不是个位数,由于字符串的valid特性,数字也不会出现在字符串的末尾,因此可以判断出连续出现的数字,并用Integer.parseInt(s.substring(start, i + 1))进行转换。

class Solution {    public String decodeString(String s) {        Stack<Integer> num = new Stack<>();        Stack<String> res = new Stack<>();        res.push("");        for (int i = 0; i < s.length(); i++){            if (s.charAt(i) >= '0' && s.charAt(i) <= '9'){                int start = i;                while (s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9'){                    i++;                }                num.push(Integer.parseInt(s.substring(start, i + 1)));            }            else if (s.charAt(i) == '['){                res.push("");            }            else if (s.charAt(i) == ']'){                String tmp = res.pop();                String tmpStr = "";                int n = num.pop();                for (int j = 0; j < n; j++){                    tmpStr = tmpStr + tmp;                }                res.push(res.pop() + tmpStr);            }            else{                res.push(res.pop() + s.charAt(i));            }        }        return res.pop();    }}