leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解

来源:互联网 发布:有限元软件开发 编辑:程序博客网 时间:2024/06/06 20:10

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”.

这道题十分简单,就是做一个遍历即可,按照规则直接展开即可

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>using namespace std;class Solution {public:    string decodeString(string s)     {        return getAll(s);    }    string getAll(string s)    {           if (s.find('[') == s.npos)            return s;        else        {            int start = s.find_first_of('[');            stack<char> skt;            int i = 0;            for (i = start; i < s.length(); i++)            {                if (s[i] == '[')                    skt.push(s[i]);                else if (s[i] == ']')                {                    skt.pop();                    if (skt.empty())                        break;                  }            }            string left = s.substr(0, start);            string cen = s.substr(start + 1, i - start - 1);            string right = s.substr(i+1);            string num = "";            for (int i = left.length() - 1; i >= 0; i--)            {                if (left[i] >= '0' && left[i] <= '9')                    num = left[i] + num;                else                    break;            }            stringstream ss;            ss << num;            int size = 0;            ss >> size;            string res = "";            for (int i = 0; i < size; i++)                res += cen;            left = left.substr(0,left.length()-num.length());            string finRes = (left + res + right);            return getAll(finRes);        }    }};
原创粉丝点击