玩命加载中 . . .

394-字符串解码


LeetCode 394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly ktimes. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are 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 will not be input like 3a or 2[4].

Example 1:

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

method

遍历字符串有4种情况

  • 数字就num累计
  • 字母res也累计
  • 遇到左括号[,就把数字和字母入栈
  • 遇到右括号],把数字栈弹出为count,当前res重复count次,累计到字符串栈上去,然后弹出为res
string decodeString(string s) {
    stack<int> nums;
    stack<string> strs;
    int num = 0;
    string res = "";
    for (int i = 0; i < s.size(); i++) {
        if (isdigit(s[i])) {
            num = num * 10 + s[i] - '0';    // num累计
        }
        else if (isalpha(s[i])) {
            res = res + s[i];   // res累计
        }
        else if (s[i] == '[') { // num和res入栈
            nums.push(num);
            num = 0;
            strs.push(res);
            res = "";
        }
        else {
            int count = nums.top(); // 弹出重复次数
            nums.pop();
            for (int j = 0; j < count; j++) {
                strs.top() += res;  // res重复count次,累计到栈顶
            }
            res = strs.top();   // 弹出为res
            strs.pop();
        }
    }
    return res;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录