Sunday, October 16, 2016

Decode String -- LeetCode

[Question]
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 kis 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".

[Analysis]
Use stack and push every character into stack until encounter ']'. When ']' is encountered, the deepest encoded sub string, in the stack, can be decoded. Push the decoded sub string back to stack and continue the process until reaching the end of the string. 
The time complexity is O(N), N is the size of the input string. Note: it is better to have a stack of "string" instead of "char" for convenience.
[Solution]
class Solution {
public:
    string decodeString(string s) {
        stack<string> st;
     
        for (auto& c: s) {
            if (c!=']') {
                st.push(string(1, c));
                continue;
            }
            //c==']'
            string item;
            string cnt;
            while(!st.empty() && st.top()!="[" ) {
                item= st.top() + item;
                st.pop();
            }
         
            if (st.top()=="[") {
                st.pop();
                while (!st.empty() && isdigit(st.top()[0]) ) {
                    cnt=st.top()+cnt;
                    st.pop();
                }
            }

            string buf="";
            for(int i=0; i<stoi(cnt); i++) {
                buf+=item;
            }
            st.push(buf);
        }
     
        string rslt;
        while (!st.empty()) {
            rslt = st.top() + rslt;
            st.pop();
        }
        return rslt;
    }

};

No comments:

Post a Comment