美文网首页
Decode String

Decode String

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-05-15 19:50 被阅读63次

题目来源
s = "3[a]2[bc]", return "aaabcbc".
解码字符串的题。然后我搞了搞,代码如下:

class Solution {
public:
    string decodeString(string s) {
        int n = s.size();
        vector<string> stack;
        for (int i=0; i<n; i++) {
            if (s[i] != ']')
                stack.push_back(string(1, s[i]));
            else {
                string str = "";
                while (stack.back() != "[") {
                    str = stack.back() + str;
                    stack.pop_back();
                }
                stack.pop_back();
                int mul = 1;
                int times = 0;
                while (!stack.empty() && stack.back() <= "9" && stack.back() >= "0") {
                    times += (stack.back()[0] - '0') * mul;
                    mul *= 10;
                    stack.pop_back();
                }
                string tmp = str;
                for (int i=0; i<times-1; i++)
                    str += tmp;
                stack.push_back(str);
            }
        }
        string res = "";
        for (int i=0; i<stack.size(); i++)
            res += stack[i];
        return res;
    }
};

能AC,但是感觉比较繁琐,应该有简洁点的解法。

class Solution {
public:
    string decodeString(const string& s, int& i) {
        string res; 
        while (i < s.length() && s[i] != ']') {
            if (!isdigit(s[i]))
                res += s[i++];
            else {
                int n = 0;
                while (i < s.length() && isdigit(s[i]))
                    n = n * 10 + s[i++] - '0';      
                i++; // '['  数字之后肯定是[,因为不存在3a这种形式。
                string t = decodeString(s, i);
                i++; // ']'
                while (n-- > 0)
                    res += t;
            }
        }
        return res;
    }

    string decodeString(string s) {
        int i = 0;
        return decodeString(s, i);
    }
};

相关文章

网友评论

      本文标题:Decode String

      本文链接:https://www.haomeiwen.com/subject/sjahxxtx.html