Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

Solution

public class Solution {
    public String decodeString(String s) {
        if(s == null) return null;
        String ans = "";
        int i = 0;
        while(i < s.length()) {
            char c = s.charAt(i);
            if( (c - '0') >= 0 && (c - '0') < 10) {
                // a number, load in all the number
                String numStr = "";
                while( (s.charAt(i) - '0' >= 0) && (s.charAt(i) - '0' < 10) ) {
                    numStr = numStr + s.charAt(i); 
                    i++;
                }

                //assert s.charAt(i) == '['
                int num = Integer.valueOf(numStr);

                int j = i + 1;
                int bracket = 1;
                while(true) {
                    if(s.charAt(j) == ']') {
                        bracket--;
                        if(bracket == 0) {
                            break;
                        }
                    } else if(s.charAt(j) == '[') {
                        bracket++;
                    }
                    j++;
                }
                String repeatS = s.substring(i+1, j);
                String spread = decodeString(repeatS);
                for(int k = 0; k < num; k++) {
                    ans = ans + spread;
                }
                i = j + 1;
            } else {
                ans = ans + c;
                i++;
            }
        }
        return ans;
    }
}

results matching ""

    No results matching ""