Leetcode 394. 字符串解码

文章目录

  • 题目
  • 代码(首刷看解析)
  • 代码(7.15 二刷自解)

题目

Leetcode 394. 字符串解码_第1张图片
Leetcode 394. 字符串解码

代码(首刷看解析)

要是面试让我遇到这个题,我会把面试官砍了的~

这个题只有无休止的细节,debug一整天

class Solution {
public:
    string getDigits(string &s, size_t &ptr) {
        string ret = "";
        while (isdigit(s[ptr])) {
            ret.push_back(s[ptr++]);
        }
        return ret;
    }

    string getString(vector <string> &v) {
        string ret;
        for (const auto &s: v) {
            ret += s;
        }
        return ret;
    }

    string decodeString(string s) {
        vector <string> stk;
        size_t ptr = 0;

        while (ptr < s.size()) {
            char cur = s[ptr];
            if (isdigit(cur)) {
                // 获取一个数字并进栈
                string digits = getDigits(s, ptr);
                stk.push_back(digits);
            } else if (isalpha(cur) || cur == '[') {
                // 获取一个字母并进栈
                stk.push_back(string(1, s[ptr++])); 
            } else {
                ++ptr;
                vector <string> sub;
                while (stk.back() != "[") {
                    sub.push_back(stk.back());
                    stk.pop_back();
                }
                reverse(sub.begin(), sub.end());
                // 左括号出栈
                stk.pop_back();
                // 此时栈顶为当前 sub 对应的字符串应该出现的次数
                int repTime = stoi(stk.back()); 
                stk.pop_back();
                string t, o = getString(sub);
                // 构造字符串
                while (repTime--) t += o; 
                // 将构造好的字符串入栈
                stk.push_back(t);
            }
        }

        return getString(stk);
    }
};


代码(7.15 二刷自解)

class Solution {
public:
    string getNum(string& s, int& i) {
        string res;
        while(isdigit(s[i]))
            res += s[i++];
        return res;
    }
    string getString(vector<string>& sub) {
        string res;
        for(string& s : sub) {
            res += s;
        }
        return res;
    }
    string decodeString(string s) {
        int i = 0;
        vector<string> stk;
        while(i < s.size()) {
            if(isdigit(s[i])) {
                stk.push_back(getNum(s, i)); // 数字
            } else if(isalpha(s[i]) || s[i] == '[') {
                stk.push_back(string(s, i++, 1));
            } else {    // ']'
                i++;
                vector<string> sub;
                while(stk.back() != "[") {
                    sub.push_back(stk.back());
                    stk.pop_back();
                }
                reverse(sub.begin(), sub.end());
                stk.pop_back(); // '['
                int num = stoi(stk.back()); // 重复次数
                stk.pop_back();
                string tmp1, tmp2 = getString(sub);
                while(num--) tmp1 += tmp2;
                stk.push_back(tmp1);
            }
        }
        return getString(stk);
    }
};

你可能感兴趣的:(Leetcode专栏,leetcode,算法)