simple 20 line DFS java solution


  • 0
    C
    public String decodeString(String s) {
            return dfs(s, new int[]{0});
        }
        private String dfs(String s, int[] pos){
            int num = 0;
            StringBuilder cursb = new StringBuilder();
            for(;pos[0]<s.length();pos[0]++){
                if(Character.isDigit(s.charAt(pos[0])))
                    num = num * 10 + (int)(s.charAt(pos[0]) - '0');
                else if(s.charAt(pos[0]) == '['){
                    pos[0]++;
                    String str = dfs(s, pos); //recursive call here
                    while(num > 0) {
                        cursb.append(str);
                        num--;
                    }
                }else if(s.charAt(pos[0]) == ']'){
                    return cursb.toString();
                }else cursb.append(s.charAt(pos[0]));
            }
            return cursb.toString();
        }
    

Log in to reply
 

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