56.Decode String(解码字符串)

Level:

  Medium

题目描述:

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

思路分析:

  设置两个栈,一个栈countstack保存方框内字符串的重复次数,一个栈resstack保存目前解码的字符串,用res记录结果,当遇到字符' ] '时,我们弹出countstack的栈顶元素reaptetime,然后将res重复reaptetime次,放入resstack栈中。

代码:

public class Solution{
    public String decodeString(String s){
        Stack<Integer>countstack=new Stack<>();
        Stack<String>resstack=new Stack<>();
        String res=""; //保存最终结果
        int i=0;
        while(i<s.length()){
            if(Character.isDigit(s.charAt(i))){ //计算重复次数
                int count=0;
                while(Character.isDigit(s.charAt(i))){
                    count=count*10+(s.charAt(i)-'0');
                    i++;
                }
                countstack.push(count);
            }else if(s.charAt(i)=='['){
                resstack.push(res); //将之前解码的字符串存放到栈中
                res="";  //重置res
                i++;
            }else if(s.charAt(i)==']'){
                int reaptetime=countstack.pop();
                StringBuilder temp=new StringBuilder();
                for(int j=0;j<reaptetime;j++){
                    temp.append(res);
                }
                res=resstack.pop()+temp.toString();//当前解码结果
                i++;
            }else{
                res=res+s.charAt(i);
                i++;
            }
        }
        return res;
    }
}
posted @ 2019-06-26 13:49  yjxyy  阅读(166)  评论(0编辑  收藏  举报