LeetCode——Decode String

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 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

用两个栈实现。

Code

class Solution {
public:
    string decodeString(string s) {
        string res = "";
        for (int i = 0; i < s.length(); i++) {
            if ((s[i] >= 'a' && s[i] <= 'z') || s[i] == '[') {
                // 10[leetcode]ef, 处理ef
                if (nums.empty()) {
                    res += s[i];
                } else
                    letters.push(s[i]);
            }

            if (s[i] >= '0' && s[i] <= '9') {
                string tmp = "";
                tmp += s[i];
                // 处理多个连续的数字
                for (int j = i + 1; j < s.length(); j++) {
                    if (s[j] >= '0' && s[j] <= '9') {
                        tmp += s[j];
                        i++;
                    }
                    else
                        break;
                }

                stringstream ss;
                ss << tmp;
                int value;
                ss >> value;
                nums.push(value);
            }
            if (s[i] == ']') {
                int value = nums.top();
                nums.pop();
                string tmp = "";
                while (1) {
                    char c  = letters.top();
                    if (c != '[')
                        tmp += c;
                    letters.pop();
                    if (c == '[')
                        break;
                }
                reverse(tmp.begin(), tmp.end());
                string tmp2 = "";
                for (int i = 0; i < value; i++) {
                    tmp2 += tmp;
                }
                // 如果为空了,就直接累加到结果里,否则压入栈中
                if (nums.empty()) {
                    res += tmp2;
                } else {
                    for (int i = 0; i < tmp2.length(); i++)
                        letters.push(tmp2[i]);
                }
            }
        }
        return res;
    }
    stack<int> nums;
    stack<char> letters;
};
posted @ 2017-09-24 22:32  清水汪汪  阅读(221)  评论(0编辑  收藏  举报