算法练习(3)—— 栈
来源:互联网 发布:怎么修复excel软件 编辑:程序博客网 时间:2024/06/05 20:44
算法练习(3)—— 栈
习题
本次题目取自leetcode中的 Depth-first Search
栏目中的第394题:
Decode String
上题:
Description
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].
Example
s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.
思路与代码
1.题意还是挺简单的。就是让你重复输出某些字符,而且题目也说了不会给你错误的形式。不过这里说一下leetcode测试代码的两个样例,一个是 ""
,一个是 "leetcode"
,这两个一个是没有输入,一个是没有 []
的形式。要自己注意加特殊判断…
2.归类于深搜,但是看到这种有多层的而且是最里层最先得到结果的,第一时间想到的就是栈了。具体想法就是把数字和字母分类压两个栈,根据 ]
来进行出栈输出。写的比较不简洁,主要是因为根据测试代码改了好几遍…不过应该还是能看懂吧~
代码如下:
#include <string>#include <stack>using namespace std;class Solution {public: string decodeString(string s) { if (s.length() == 0) return ""; int i = 0; stack<int> num; stack<string> result; while (i < s.length()) { if (isNumber(s[i])) { int start = i; while (isNumber(s[i + 1])) i++; int count = 0, mul = 1; for (int j = i; j >= start; j--) { count += (s[j] - '0') * mul; mul *= 10; } num.push(count); } else if (s[i] == '[') { result.push(""); } else if (s[i] == ']') { string ss = result.top(); result.pop(); int repeat = num.top(); num.pop(); string r = ""; for (int k = 0; k < repeat; k++) r += ss; if (!result.empty()) { string next = result.top(); result.pop(); result.push(next + r); } else { result.push(r); } } else { if (!result.empty()) { string next = result.top(); result.pop(); result.push(next + s[i]); } else { string ss = ""; ss += s[i]; result.push(ss); } } i++; } return result.top(); } bool isNumber(char ch) { if (ch <= '9' && ch >= '0') return true; return false; }};
- 算法练习(3)—— 栈
- 算法练习笔记(15)—— 哈希表的练习
- Java基础算法练习五题——(3)
- 算法练习(5) —— 图
- 算法练习笔记(五)— 图
- 排序算法自我练习(四)——归并算法
- 算法练习(4)—— 贪心算法
- 算法练习(6) —— 贪心算法
- 算法练习笔记(三)— 分治算法
- 算法练习笔记(四)— 分治算法
- 算法练习——Multithreading
- 算法练习——List_Throw
- 算法练习——最小公倍数
- 算法练习——“百钱买百鸡”
- 分治算法——算法练习
- 筛选算法——算法练习
- 算法练习—状态转移算法
- 排序算法自我练习(一)——冒泡排序
- ACM-ICPC(2017)北京赛区网络赛-E-Territorial Dispute(计算几何->凸包)
- 调整数组顺序使奇数位于偶数前面
- NodeManager代码分析之NodeManager启动过程
- Redis学习02——Jedis使用
- mybatis入门基础(十)-----分页查询
- 算法练习(3)—— 栈
- 求排列的逆序数
- struts2写web层的项目,页面显示总是路径更改不了。或是路径改了,但效果运行不出来。【双清:ctrl+shift+delete清浏览器缓存;Tomcat 右键clean,清理Tomcat缓存。】
- wr720n v4 折腾笔记(三):网络配置与扩充USB
- 文章标题
- YARNMRv2 Node Manager深入剖析—NodeManager启动Container流程分析
- 购房卖方违约 买方如何维护自己的合法权益?
- mybatis入门基础(十一)-----分页查询原理详解
- Hadoop2.x 让你真正明白yarn