Stack的应用——Decode String
来源:互联网 发布:网上比价软件下载 编辑:程序博客网 时间:2024/06/18 08:18
题解:
1.问题描述:给定一个编码字符串,返回它的解码字符串。编码规则是:k [encoded_string],其中方括号内的encoded_string被重复k次。 注意,k被保证为正整数。
2.解题思路:
s = "3[a2[c]]", return "accaccacc".
通过这个例子,可以看出需要从内向外逐步展开括号来得到最终的解码字符串。
参考了数据结构书上的括号匹配的算法之后,可以类似得到这道题的算法:
创建一个栈stk用来存放字符
for 字符串 s 中的每一个字符 ch
if ch 不是右方括号 ]
将ch压入栈中
else
声明一个空串temp用来记录 [ ] 之间的内容
while 栈顶元素不是左方括号 [
temp = 栈顶元素 + temp
弹出栈顶元素
弹出左方括号 [
声明一个num用来记录k
while 栈不空且栈顶元素为数字
在num上不断叠加
弹出栈顶元素
向stk中push num次的temp
声明一个空字符串ss并赋予stk中的内容
返回ss
源代码如下:
#include <iostream>
#include <stack>#include <string>
using namespace std;
class Solution {
public:
string decodeString(string s) {
stack<char> result;
for(int i=0;i<s.size();i++)
{
if(s[i]!=']')
result.push(s[i]);
else
{
string temp="";
while(result.top()!='[')
{
temp=result.top()+temp;
result.pop();
}
result.pop();
int num=0;
int c=1;
while(!result.empty()&&result.top()>='0'&&result.top()<='9')
{
num+=(result.top()-48)*c;
c*=10;
result.pop();
}
for(int x=0;x<num;x++)
{
for(int y=0;y<temp.size();y++)
result.push(temp[y]);
}
}
}
string decoded="";
while(!result.empty())
{
decoded=result.top()+decoded;
result.pop();
}
return decoded;
}
};
0 0
- Stack的应用——Decode String
- [Leetcode-394]【Stack】Decode String
- leetcode——Decode String
- Leetcode394——Decode String
- LeetCode—394. Decode String
- LeetCode—394. Decode String
- stack的应用——Web Navigation
- decode函数的应用
- Stack的应用——符号匹配问题
- Stack(栈)的简单应用——实现单词逆序
- Stack的应用——Binary Tree Preorder Traversal
- 【leetcode】String——Decode Ways(91)
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Decode String
- Javascript 正则表达式笔记
- 关于vs2015+qwt配置的时的一些问题
- web实现轮播图
- 算法1:博弈论
- 5-6 逆序的三位数 (10分)
- Stack的应用——Decode String
- Java中网络IO的实现方式-BIO、NIO、AIO
- java
- Python爬虫实战——代理IP全部抓取
- 如何看待华为要求清理34岁以上的员工?
- SharePoint 2016 配置用户请求应用程序
- 5-7 I Love GPLT (5分)
- C语言小程序——数的重组
- java入门