leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解
来源:互联网 发布:有限元软件开发 编辑:程序博客网 时间:2024/06/06 20:10
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”.
这道题十分简单,就是做一个遍历即可,按照规则直接展开即可
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>using namespace std;class Solution {public: string decodeString(string s) { return getAll(s); } string getAll(string s) { if (s.find('[') == s.npos) return s; else { int start = s.find_first_of('['); stack<char> skt; int i = 0; for (i = start; i < s.length(); i++) { if (s[i] == '[') skt.push(s[i]); else if (s[i] == ']') { skt.pop(); if (skt.empty()) break; } } string left = s.substr(0, start); string cen = s.substr(start + 1, i - start - 1); string right = s.substr(i+1); string num = ""; for (int i = left.length() - 1; i >= 0; i--) { if (left[i] >= '0' && left[i] <= '9') num = left[i] + num; else break; } stringstream ss; ss << num; int size = 0; ss >> size; string res = ""; for (int i = 0; i < size; i++) res += cen; left = left.substr(0,left.length()-num.length()); string finRes = (left + res + right); return getAll(finRes); } }};
阅读全文
0 0
- leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解
- LeetCode-394. Decode String (JAVA)解码字符串
- leetcode 97. Interleaving String(字符串交错出现) DFS深度优先遍历+DP
- leetcode 91. Decode Ways DP动态规划+DFS深度优先遍历
- Leetcode 394. Decode String 字符串解码 解题报告
- LeetCode 之 DFS 深度优先遍历
- leetcode 606. Construct String from Binary Tree 前序遍历 + 深度优先遍历DFS
- 深度优先遍历DFS
- DFS-深度优先遍历
- DFS深度优先遍历
- 深度优先遍历(DFS)
- DFS 深度优先遍历
- 深度优先遍历!!DFS
- DFS 深度优先遍历
- 深度优先遍历DFS
- 394. Decode String (解码字符串)
- Decode string----字符串解码问题
- leetcode 22. Generate Parentheses DFS深度优先遍历
- 使用java程序启动linux上的脚本,重启tomcat
- 数据库中的事务和锁
- 移动端获取地理定位
- Angular4配置host后执行ng serve报Provided host a.api.***.com could NOT be bound...
- Linux内存计算
- leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解
- 自我介绍
- unity shader
- 基于Arduino Pro mini的语音彩灯播报系统
- laravel 快递100 api的使用
- springMVC中两种validation 实现接口与注解
- mysql 转换NULL数据方法
- RXTX 串口程序调试 -java
- SmartGit —— 体验过期解决办法