Share a Java O(n) recursive solution - 3ms


  • 0
    J

    Similar to idea of checking valid number.

    public class Solution {
        private int pos = 0;
        
        public String decodeString(String s){
            StringBuilder str = new StringBuilder();
            int start = pos;
            while(pos<s.length()&&s.charAt(pos)!=']'){
                start=pos;
                while(pos<s.length()&&Character.isLetter(s.charAt(pos))) pos++;
                str.append(s.substring(start,pos));
                start=pos;
                while(pos<s.length()&&Character.isDigit(s.charAt(pos))) pos++;
                int k = (pos>start)?Integer.parseInt(s.substring(start,pos)):1;
                if(pos<s.length()&&s.charAt(pos)=='['){
                    pos++;
                    String next = decodeString(s);
                    for(int l=0;l<k;l++) str.append(next);
                }
            }
            if(pos<s.length()&&s.charAt(pos)==']') pos++;
            return str.toString();
        }
    }
    
    

Log in to reply
 

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