share my java solution!


  • 0
    T
    public class Solution {
        public String decodeString(String s) {
            if(s==null || s.length()<1) return s;
            
            char[] array=s.toCharArray();
            
            Deque<Integer> num_stack=new ArrayDeque<>();
            Deque<String> str_stack=new ArrayDeque<>();
            
            int num=1;
            String str="";
            for(int i=0;i<array.length;i++){
                if(Character.isDigit(array[i])){
                    num=array[i]-'0';
                    while(i+1<array.length&&Character.isDigit(array[i+1])){
                        i++;
                        num=num*10+array[i]-'0';
                    }
                }else if(array[i]=='['){
                    num_stack.offer(num);
                    str_stack.offer(str);
                    str="";
                }else if(array[i]==']'){
                    int count=num_stack.pollLast();
                    StringBuilder sb=new StringBuilder();
                    for(int j=0;j<count;j++){
                        sb.append(str);
                    }
                    
                    if(!str_stack.isEmpty()){
                        str=str_stack.pollLast()+sb.toString();
                    }else{
                        str=sb.toString();
                    }
                }else{
                    str+=array[i];
                }
            }
            
            return str;
        }
    }
    

Log in to reply
 

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