Java 3ms solution by 2stacks


  • 0
    X

    public class Solution {

    public String decodeString(String s) {
        int len=s.length();
        if(len==0||s==null){
            return "";
        }
        Stack<Integer> times=new Stack<Integer>();
        Stack<String> stack=new Stack<String>();
        String cur="";
        char[] schar=s.toCharArray();
        int i=0;
        while(i<len){
            if(Character.isDigit(schar[i])){
                int num=0;
                while(i<len&&Character.isDigit(schar[i])){
                    num=num*10+schar[i]-'0';
                    i++;
                }
                times.push(num);
            }else{
                if(schar[i]=='['){
                    stack.push(cur);
                    cur="";
                }else if(schar[i]==']'){
                    StringBuilder sb=new StringBuilder();
                    int n=times.pop();
                    for(int j=0;j<n;j++){
                        sb.append(cur);
                    }
                    sb.insert(0,stack.pop());
                    cur=sb.toString();
                }else{
                    cur+=schar[i];
                }
                i++;
            }
        }
        return cur;
    }
    

    }


Log in to reply
 

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