LeetCode解题报告 394. Decode String [medium]
来源:互联网 发布:多个虚拟机网络设置 编辑:程序博客网 时间:2024/06/05 01:56
题目描述
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]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc".s = "3[a2[c]]", return "accaccacc".s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
解题思路
题目的show tags 指出是dfs和stack相关,因此考虑用栈来实现。
可以看到字符串中字符出现的顺序一定是:数字--> [ --> 字母 --> ] ,以这四个为一组。建立两个栈,一个栈a用来存储这一组中的这一个数字,表明重复的次数。另一个栈b用来存储之前已经解码好的字符串(仍然以这样的四个为一组解码好的)。用 [ 和 ] 标识进栈和出栈。每次在遇到 [ 之后,就让数字(count来标识)进栈a,进栈以后立即让count归0,为了记录下一个数字。再让已经解码好的result字符串进栈,进栈以后result重置为空,为了存储接下来会遇到的字母(四个为一组到了第三个)。最后在遇到 ] 之后,对result重复栈a的数字的n-1次(已经有一次), 将之前栈b的字符串和result加起来为新的reslut就是这四个为一组解码好的加上之前已经解码好的字符串。将栈a,栈b出栈,也就是变为空栈。
最后不断这样重复,返回result。
复杂度分析
class Solution {public: string decodeString(string s) { stack<int>numbers; stack<string>chars; int count=0; string result=""; for (int i=0; i<s.size(); i++) { if (isdigit(s[i])) { count=count*10+s[i]-'0'; } else if (s[i]=='[') { chars.push(result); numbers.push(count); result=""; count=0; } else if (isalpha(s[i])) { result.push_back(s[i]); } else if (s[i]==']'){ string temp=result; for (int j=0; j<numbers.top()-1; j++) { result=result+temp; } result=chars.top()+result; chars.pop(); numbers.pop(); } } return result; }};
- LeetCode解题报告 394. Decode String [medium]
- [leetcode] 394. Decode String 解题报告
- LeetCode 394. Decode String 解题报告
- [LeetCode] 394. Decode String 解题报告
- [Leetcode] 394. Decode String 解题报告
- Leetcode 394. Decode String[medium]
- Leetcode 394. Decode String 字符串解码 解题报告
- 394.leetcode Decode String(medium)[栈 字符串]
- LeetCode #394 - Decode String -Medium
- Leetcode Decode Ways 解题报告
- 394. Decode String 难度:medium
- LeetCode解题报告 53. Maximum Subarray [medium]
- LeetCode解题报告 338. Counting Bits [medium]
- LeetCode解题报告 413. Arithmetic Slices [medium]
- LeetCode解题报告 343. Integer Break [medium]
- LeetCode解题报告 392. Is Subsequence [medium]
- LeetCode解题报告 120. Triangle [medium]
- LeetCode解题报告 279. Perfect Squares [medium]
- kubernets 权威指南
- Java多线程
- Selenium2(WebDriver)总结(二)---Firefox的firebug插件参数设置(补充)
- iOS开发中一些需要授权的功能在plist中添加的字段白名单
- Bash别名与函数实战攻略
- LeetCode解题报告 394. Decode String [medium]
- HTML5基础(Web Storage)
- Python爬虫 分组 和 (.*?)
- mysql常用参数汇总
- MyBatis 和 Hibernate对比与选择
- Android TextView中文字通过SpannableString来设置超链接、颜色、字体等属性
- 标准IO与文件IO
- Maven入门
- 第一个 Spring Boot 程序