Depth-first Search -- Leetcode problem394. Decode String

来源:互联网 发布:淘宝能赚到钱吗 编辑:程序博客网 时间:2024/05/19 02:23
  • 描述: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”.

  • 分析:这道题是要求按照所给的数字和字符串组成一个新的字符串,数字代表个数,[]中的元素代表要进行重复的字符串。
  • 思路一:利用递归求解。
class Solution {public:    string findString(const string &s, int &i) {    string res;    while (i < s.length() && s[i] != ']') {        if (s[i] < '0' || s[i] > '9') {            res += s[i];            i++;        } else {            int mul = 0;            while (i < s.length() && s[i] >= '0' && s[i] <= '9') {                mul = mul * 10 + s[i] - '0';                i++;            }            i++;            string temp = findString(s, i);            i++;            while (mul > 0) {                res += temp;                mul--;            }        }    }    return res;}string decodeString(string s) {        int i = 0;        return findString(s, i);}};
原创粉丝点击