Leetcode之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 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".

代码:

方法一——递归法:

class Solution {
public:
    string decodeString(string s) {
        int i = 0;
        return decode(s, i);
    }
    string decode(string s, int& i) {
        string res = "";
        int n = s.size();
        while (i < n && s[i] != ']') {
            if (s[i] < '0' || s[i] > '9') {
                res += s[i++];
            } else {
                int cnt = 0;
                while (s[i] >= '0' && s[i] <= '9') {
                    cnt = cnt * 10 + s[i++] - '0';
                }
                ++i;
                string t = decode(s, i);
                ++i;
                while (cnt-- > 0) {
                    res += t;
                }
            }
        }
        return res;
    }
};

思路:调用一个递归函数decode进行对s的解析,在左括号前的一定是数字,根据这一点。如果遇到了字母,直接加到结果中,如果遇到了数字,记录这个数字,然后++i跳过左括号,进行下一步解析,对下一步解析的结果进行数字n的循环加到结果中。然后++i,跳过右括号。解析函数中的while循环结条件是i<n且s[i]不是右括号。每一步循环的解析结果会返回第一个右括号前的解析。了解理解这个流程。

方法二——迭代法:

class Solution {
public:
    string decodeString(string s) {
        string t = "";
        stack<int> s_num;
        stack<string> s_str;
        int cnt = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] >= '0' && s[i] <= '9') {
                cnt = 10 * cnt + s[i] - '0';
            } else if (s[i] == '[') {
                s_num.push(cnt);
                s_str.push(t);
                cnt = 0; t.clear();
            } else if (s[i] == ']') {
                int k = s_num.top(); s_num.pop();
                for (int j = 0; j < k; ++j) s_str.top() += t;
                t = s_str.top(); s_str.pop();
            } else {
                t += s[i];
            }
        }
        return s_str.empty() ? t : s_str.top();
    }
};

思路:使用两个栈 ,一个是数字栈,一个是字符串栈,对s进行遍历,当遇到了数字,另cnt等于数字;当遇到了左括号,将数字和字符串存到栈中,数字和字符串清零;当遇到了右括号,取栈顶的数字k,给栈顶的字符串进行对于t的k次叠加,然后令t等于字符串栈顶的字符串;当遇到字母,直接往t上加。最后返回的时候,如果字符串栈为空,那么返回t,如果字符串栈不是空,那么返回栈顶的字符串。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章