力扣Java版个人代码分享-栈篇(字符串解码)

206. 字符串解码

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

例子

例子1:
输入:s = “3[a]2[bc]”
输出:“aaabcbc”
例子2:
输入:s = “3[a2[c]]”
输出:“accaccacc”
例子3:
输入:s = “2[abc]3[cd]ef”
输出:“abcabccdcdcdef”
例子4:
输入:s = “abc3[cd]xyz”
输出:“abccdcdcdxyz”

代码

代码来自leetcode @huang

    public String decodeString(String s) {
    
    
        //注意给个泛型
        Stack<String> stack = new Stack<String>();
        for(int i=0;i<s.length();i++) {
    
    
            if(s.charAt(i) == ']'){
    
    
                String string="";
                //这里要注意 是字符串 不是字符
                while(!stack.peek().equals("[")){
    
    
                    string = stack.pop() + string;
                }
                stack.pop();
                String countString="";
                while((!stack.isEmpty())&&(stack.peek().charAt(0)>='0'&&stack.peek().charAt(0)<='9')) {
    
    
                    countString=stack.pop()+countString;
                }
                int count=Integer.parseInt(countString);
                String retString="";
                for (int j = 0; j < count; j++) {
    
    
                    retString = retString + string;
                }
                stack.push(retString);
            }else{
    
    
                String str=""+s.charAt(i);
                stack.push(str);
            }
        }
        String s1 = "";
        while(!stack.isEmpty()){
    
    
            s1 = stack.pop() + s1;
        }
        return s1;
    }

思路

(1)对s字符串从左往右判断有没有"]",没遇到之前拼接到temp字符串。
(2)当遇到"]“时,对temp字符串从右到左拼接到String字符串上面,当遇到”["时停止。
(3)接着第二步后,继续取出数字count,通过数字count和字符串String得出的字符串压入栈。
(4)前三步循环到s字符串结束,并取出栈里面的字符串拼接并输出。

注意事项

初始化栈的时候记得给个泛型

待优化

猜你喜欢

转载自blog.csdn.net/northern0407/article/details/108292073
今日推荐