Decode String(leetcode),solved by DFS
来源:互联网 发布:汇天下p2p源码 编辑:程序博客网 时间:2024/05/21 11:37
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、 找到最外面的括号里面的子结构,对里面的结构做k次decode,逐次加到res中;
4、 判断之后还有没有字符,如果有,执行2和3步,然后把结果加到res中,否则,结束,返回res,
算法复杂度分析:这相当于图的DFS,所以算法复杂度为O(V+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;
}
};
- Decode String(leetcode),solved by DFS
- (M)DFS: 394. Decode String
- 【Leetcode】394. Decode String
- [Leetcode] Decode String
- 【leetcode】394. Decode String
- LeetCode: Decode String
- leetcode ----394. Decode String
- LeetCode[394] Decode String
- [leetcode] 394. Decode String
- [Leetcode]394. Decode String
- Leetcode Decode String
- 【LeetCode】 394. Decode String
- LeetCode 394. Decode String
- Leetcode 394. Decode String
- [leetcode]394. Decode String
- LeetCode 394. Decode String
- leetcode-394-Decode String
- Leetcode-394. Decode String
- codeforces Destroying Array 线段树维护区间
- 图像偏色检测算法,速度快,效果好,共享给大家。
- android ScrollView嵌套viewpager,viewpager嵌套gridview,解决内嵌无法显示的问题
- ubuntu下安装flash player
- 从性能指标角度看ARM Cortex-M各处理器区别
- Decode String(leetcode),solved by DFS
- 剑指offer之顺时针打印矩阵
- 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
- 角点绘制2
- 求1+2!+3!+...+20!的和。
- BNUOJ 52296 Nearest Neighbor Search(十一弱校联盟 暴力分情况)
- 【CUDA开发】Thrust库
- 【C++研发面试笔记】9. 基本数据结构-二叉查找树BST
- 利用递归方法求5!。