Easy to understand Java Solution using two Stacks(4 ms)


  • 0
    T
    public class Solution {
        
        public String decodeString(String s) {
            Stack<Integer> digits = new Stack();
            Stack<Integer> index = new Stack();
            if(s.length()==0)return "";
            int count=0;
            StringBuilder decode = new StringBuilder();
            for(int i=0;i<s.length();i++){
                char c = s.charAt(i);
                if(c>='0' && c<='9'){
                    count=count*10+c-'0';
                    continue;
                }
                if(c=='['){
                   digits.push(count);
                   index.push(decode.length());
                   count=0;
                   continue;
                }
                if(c==']'){
                    int repeat = digits.pop();
                    int indx = index.pop();
                    StringBuilder part = new StringBuilder();
                    while(--repeat>0){
                        part.append(decode.toString().substring(indx));
                        }
                    decode.append(part.toString());
                    continue;
                }
                decode.append(c);
            }
            return decode.toString();
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.