Decode String(leetcode),solved by DFS

来源:互联网 发布:汇天下p2p源码 编辑:程序博客网 时间:2024/05/21 11:37
    这次主要介绍使用深度优先搜索算法解决leetcode上面的一道题,题目如下:
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 exactlyk 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".

解题思路:因为考虑到这样结构的字符串中的括号里面可能还会嵌套类似的结构,所以我们可以采取深度优先搜索的思想解决这个问题,我们将最外面的括号里面的当作这种结构的一种子结构,所以我们在对外面的结构进行decode时,不断找到子结构,其子结构可以父结构的子节点,然后我们的方法就是DFS,优先对子结构进行处理,最后将所有的结果加起来就是我们的答案了。

算法:

1、       判断处理的字符是否为空,若是,直接返回一个空字符串;

2、       将没有数字的部分加到最终的结果res中,若是原字符串中有数字,则将数字k提取出来,以便之后循环,否则直接返回res

3、       找到最外面的括号里面的子结构,对里面的结构做kdecode,逐次加到res中;

4、       判断之后还有没有字符,如果有,执行23步,然后把结果加到res中,否则,结束,返回res

算法复杂度分析:这相当于图的DFS,所以算法复杂度为OV+E)。

具体代码如下:

 

class Solution {
public:
    string decodeString(string s) {
       string res;
  int n = s.length();
  if (n == 0)return res;
  stack<char> sc;
  string cou;
  bool b = false;
  int si = 0;
  int i = 0;
  for (; i<n; i++) {
   while (s[i] >= '0'&&s[i] <= '9'&&i<n) {
    cou += s[i];
    b = true;
    i++;
   }
   if (b)
   {
    si = atoi(cou.c_str());
    break;
   }
   else
    res += s[i];
  }
  if (i == n)return res;
  int j = i;
  for (; j<n; j++) {
   if (s[j] == '[')sc.push(s[j]);
   else if (s[j] == ']')sc.pop();
   if (sc.empty())break;
  }
  for (int k = 0; k<si; k++) {
   res += decodeString(s.substr(i + 1, j - i - 1));
  }
  if (j != n)
   res += decodeString(s.substr(j + 1, n - j));
  return res;
    }   
};
0 0