zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    Standford机器学习 聚类算法(clustering)和非监督学习(unsupervised Learning)
    cocos2d-x 消类游戏,类似Diamond dash 设计
    cocos2d-x精灵的添加和移动
    小学生四则运算测试网站文档更新
    第四次作业
    第三次作业
    第二周作业第三题_张东明
    第二章
    第二周的作业第二题_张东明
    第二次作业第3题_JH
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11089405.html
Copyright © 2011-2022 走看看