G4 - Decode String

May 21, 2017

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 :
take 2 stacks and 2 variables, numStack, resStack, num, res
on normal char append it to res
on normal number append it to the num, and push to the numStack
on opening bracket push the res to the resStack, and make res = ""
on closing bracket pop top num and str, start the result with str and append the res top num times, make it the res

                
public class Solution {
    public String decodeString(String s) {
        if(s == null || s.length() == 0){
            return "";
        }

        Stack<Integer> numStack = new Stack<Integer>();
        Stack<String> resStack = new Stack<String>();
        String res = "";
        for(int i=0; i<s.length();){
            if(Character.isDigit(s.charAt(i))){
                int cnt = 0;
                while(Character.isDigit(s.charAt(i))){
                    cnt = cnt*10 + (s.charAt(i) - '0');
                    i++;
                }
                numStack.push(cnt);
            }else if(s.charAt(i) == '['){
                resStack.push(res);
                res = "";
                i++;
            }else if(s.charAt(i) == ']'){
                int times = numStack.pop();
                String temp = resStack.pop();
                String tempres = temp;
                for(int j=0; j<times; j++){
                    tempres = tempres + res;
                }
                res = tempres;
                i++;
            }else{
                res = res + s.charAt(i);
                i++;
            }
        }
        return res;
    }
}