BiruLyu
8/21/2017 - 5:45 PM

394. Decode String(#dfs).java

public class Solution {
    public String decodeString(String s) {
        String res = "";
        Stack<Integer> countStack = new Stack<>();
        Stack<String> resStack = new Stack<>();
        int idx = 0;
        while (idx < s.length()) {
            if (Character.isDigit(s.charAt(idx))) {
                int count = 0;
                while (Character.isDigit(s.charAt(idx))) {
                    count = 10 * count + (s.charAt(idx) - '0');
                    idx++;
                }
                countStack.push(count);
            }
            else if (s.charAt(idx) == '[') {
                resStack.push(res);
                res = "";
                idx++;
            }
            else if (s.charAt(idx) == ']') {
                StringBuilder temp = new StringBuilder (resStack.pop());
                int repeatTimes = countStack.pop();
                for (int i = 0; i < repeatTimes; i++) {
                    temp.append(res);
                }
                res = temp.toString();
                idx++;
            }
            else {
                res += s.charAt(idx++);
            }
        }
        return res;
    }
}
class ReturnType {
    String val;
    int end;
    public ReturnType (String val, int end) {
        this.val = val;
        this.end = end;
    }
}

public class Solution {
    public String decodeString(String s) {
       //I add a ']' at the end of the String as a dummy parenthesis meaning we repeat the whole string one time
        s = s + ']';
        return help(s, 1, 0).val;
    }
    
    private ReturnType help(String s, int repeat, int i) {
        StringBuilder sb = new StringBuilder();
        
        for (int j = i; j < s.length(); j++) {
            if (Character.isDigit(s.charAt(j))) {
                int num = 0;
                while (Character.isDigit(s.charAt(j))) {
                    num = 10 * num + (s.charAt(j++) - '0');
                }
                ReturnType rt = help(s, num, j + 1);
                sb.append(rt.val);
             //We have to skip the chars already been encoded during the previous DFS
                j = rt.end;
            } else if (s.charAt(j) == ']') {
                String str = sb.toString();
                for (int k = 0; k < repeat - 1; k++) {
                    sb.append(str);
                }
                return new ReturnType(sb.toString(), j);
            } else if (s.charAt(j) != '[') {
                sb.append(s.charAt(j));
            } 
        }
        //Since I have already add a ']' at the end of the String, the result will return at the last index of the String inside the for loop 
        return null;
    }
}