Wednesday, June 7, 2017

394. Decode String

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:

We use one stack to store the number to repeat (count), and one stack to store the previous string.

Go through all characters in the string.

If it is a digit, calculate the new count value.

If it is a '[', we push count and the current string to both stacks, and reset count and current string.

If it is a ']', we pop the count and previous sting, repeatedly append the current string to the previous string, and form the new current string.

If it is an other character, we simply append it to the current string.

The time complexity is O(n) and the space complexity is also O(n).



Code:


public class Solution {
    public String decodeString(String s) {
        Stack<Integer> count = new Stack<>();
        Stack<StringBuilder> prev = new Stack<>();
        StringBuilder curr = new StringBuilder();
        int k = 0;
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                k = k * 10 + c - '0';
            }
            else if (c == '[') {
                count.push(k);
                prev.push(curr);
                curr = new StringBuilder();
                k = 0;
            }
            else if (c == ']') {
                StringBuilder tmp = curr;
                curr = prev.pop();
                for (int i = count.pop(); i > 0; i--) {
                    curr.append(tmp);
                }
            }
            else {
                curr.append(c);
            }
        }
        return curr.toString();
    }
}