力扣 394. 字符串解码

61 阅读1分钟

🔗 leetcode.cn/problems/de…

题目

  • 对字符串中的 k[s] 解码为 s 重复 k 次

思路

  • 碰到数字,开始进行递归 decode 展开,否则字符不解码
  • 针对于解码的部分,先明确 k 的数字是多少,再明确 [ ] 括号中的 str 是什么,最后重复 k 次
  • 注意这个过程中,要是碰到字符串是数字开头,递归进行 decode

代码

class Solution {
public:
    string decode(string s, int start, int& ori_len) {
        int index = start;
        int num = 0;
        while (s[index] != '[') {
            num = num* 10 +  s[index] - '0';
            index++;
        }

        string str;
        for (int i = index + 1; i < s.size(); i++) {
            if (s[i] == ']') {
                ori_len = i - start;
                break;
            }
            if (s[i] >= '0' && s[i] <= '9') {
                int len = 0;
                str += decode(s, i, len);
                i += len;
            } else {
                str += s[i];
            }
        }

        string ans;
        while (num--) {
            ans += str;
        }

        return ans;
    }
    string decodeString(string s) {
        string ans;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] >= '0' && s[i] <= '9') {
                int ori_len = 0;
                ans += decode(s, i, ori_len);
                i += ori_len;
            } else {
                ans += s[i];
            }
        }
        return ans;
    }
};