394. Decode String
来源:互联网 发布:4g卡显示2g网络能用吗 编辑:程序博客网 时间:2024/05/18 05:50
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
or2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc".s = "3[a2[c]]", return "accaccacc".s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
思路:一看就知道要使用 栈 来做,给出的例子都是3种不同的例子,第一个例子左右各一对括号,第二个例子括号里面包含括号,第三个例子跟第一个例子差不多,但是还有尾巴。
代码附上:
class Solution {public: string decodeString(string s) { stack<char> st; int len = s.length(); string tmp; string ret; int i; for(i=0;i<len;i++) { if(s[i]!=']') st.push(s[i]); else { while(st.top()!='[') { tmp.insert(tmp.begin(),st.top()); st.pop(); } st.pop(); // pop '[' int reapt = st.top()-'0'; string tmp_tmp = tmp; for(int i=0;i<reapt-1;i++) tmp+=tmp_tmp; st.pop(); // pop '3' if(st.empty()) { ret+=tmp; tmp=""; } } } if(i==len && !st.empty()) { string ttt; while(!st.empty()) { ttt.insert(ttt.begin(),st.top()); st.pop(); } ret += ttt; } return ret; }};提交以为会AC,结果很令人变态。。。也是我写程序没有考虑到的情况,数字连续有好几位的情况:100[abcd]. 令人崩溃了,下次来修这个bug!
0 0
- 【Leetcode】394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- 【leetcode】394. Decode String
- 394. Decode String
- leetcode ----394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- [leetcode] 394. Decode String
- [Leetcode]394. Decode String
- 394. Decode String
- 【LeetCode】 394. Decode String
- 394. Decode String
- LeetCode 394. Decode String
- Leetcode 394. Decode String
- 2016Bytecup之菜鸟进阶
- leetcode(85).383. Ransom Note
- < %=request.getParameter(“username”)% > 等价于 ${ param.username }
- Bloom Filter概念和原理
- 26. Remove Duplicates from Sorted Array
- 394. Decode String
- C/C++指向指针的指针
- Opencv+VS2010同时打开三路摄像头源代码及各类问题分析
- 设计模式-模版方法模式(8)
- 排序算法之归并排序
- 我遇到的面试题,供大家参考
- 基于Shiro的用户权限管理管理思想
- mysql大数据高并发处理
- 分布式缓存--序列4--缓存更新策略/缓存穿透/缓存雪崩