[LeetCode] 394. Decoded string (stack)

topic

Given a coded string, it returns the decoded string.

Encoding rule is: k [encoded_string], wherein the inside square brackets represents encoded_string exactly repeated k times. Note k ensure a positive integer.

You can think of the input string is always valid; the input string no extra spaces, and enter the square brackets always conform to the required format.

Further, the raw data that you can not contain numbers, all figures only represent the number of repetitions k, 3a such as an input or as 2 [4] does not occur.

Example:

s = "3 [a] 2 [bc]", Back "aaabcbc."
S = ". 3 [A2 [C]]", Back "accaccacc."
S = "2 [ABC]. 3 [CD] EF", returns "abcabccdcdcdef".

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/decode-string

answer

  • Stack.
  • Note that the number may not be a treatment.
  • Write the code may be a bit long-winded. You can pop up first and then judge, rather than the first peek. StringBuilder operation again understand the wave.

Code

class Solution {
    public String decodeString(String s) {
        if(s==null){
            return null;
        }
        Stack<Character> stack=new Stack<>();
        for(int i=0;i<s.length();++i){
            if(s.charAt(i)!=']'){
                stack.push(s.charAt(i));
            }
            else{
                StringBuilder tempS=new StringBuilder("");
                while(stack.peek()!='['){
                    tempS.append(stack.pop());
                }
                String tempStr=tempS.reverse().toString();
                stack.pop();
                
                int num=0;
                int pos=1;//
                while(!stack.isEmpty()&&stack.peek()>='0'&&stack.peek()<='9'){//
                    num+=(stack.pop()-'0')*pos;//
                    pos*=10;
                }
                while(num--!=0){
                    for(int j=0;j<tempStr.length();++j){
                        stack.push(tempStr.charAt(j));
                    }
                }
            }
        }
        StringBuilder decodedStr=new StringBuilder("");
        while(!stack.isEmpty()){
            decodedStr.append(stack.pop());
        }
        return decodedStr.reverse().toString();
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11306359.html