[leetcode] 394. Decode String

来源:互联网 发布:css编程 编辑:程序博客网 时间:2024/06/05 17:15

Question:

Given an encoded string, return it’s 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".

Solution:

“a3[a]a2[bc]a”对于这样一个字符串,用递归的思路,设一开始为1[str]这样,就把str decode就可以了,对于str里面形如str这样的encoded的字符串,继续递归得到[]里的字符串就好。
当在遇到数字num之后,肯定会遇到n个’[‘,然后遇到n个’]’后就可以视为decode完了num个[]里的内容,继续往右遍历(对应代码中的第一个if)
第二个if处理正常的字符
第三个if是对于突然遇到的一个’]’,则说明当前函数并不是最一开始调用的函数,则重复times次后返回即可。
(我承认代码写得确实有点乱,思路也不好表达出来~)

class Solution {public:    string decodeString(string s) {        return helper(1, s, 0);    }    string helper(int times, string & s, int k) {        string tmp = "";        for (int i = k; i < s.size(); i++) {            if (s[i] >= '1' && s[i] <= '9') {                string num = "";                num += s[i++];                while (s[i] >= '0' && s[i] <= '9')                    num += s[i++];                tmp += helper(stoi(num), s, i+1);                int count = 1;                while (count != 0) {                    i++;                    if (s[i] == '[')                        count++;                    if (s[i] == ']')                        count--;                }            } else if (s[i] != ']') {                tmp += s[i];            } else if (s[i] == ']') {                string ret = "";                for (int j = 0; j < times; j++)                    ret += tmp;                return ret;            }        }        string ret = "";        for (int j = 0; j < times; j++)            ret += tmp;        return ret;    }};

Solution2:

居然在discuss里找到了和我一样思路的一份代码,这份代码比我的要好,主要是因为全过程只使用一个i来遍历字符串,而省去了我在第一个if里面的第二个while的找到当前遇到的数字对应的要解码的内容,因为他递归下一次的时候,就完成了i不断++到合适的‘]’结束的位置。
学习了。

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++; // '['                string t = decodeString(s, i);                i++; // ']'                while (n-- > 0)                    res += t;            }        }        return res;    }    string decodeString(string s) {        int i = 0;        return decodeString(s, i);    }};