首页 技术 正文
技术 2022年11月12日
0 收藏 631 点赞 3,107 浏览 1360 个字

Question

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".

Solution

用两个栈实现。

Code

class Solution {
public:
string decodeString(string s) {
string res = "";
for (int i = 0; i < s.length(); i++) {
if ((s[i] >= 'a' && s[i] <= 'z') || s[i] == '[') {
// 10[leetcode]ef, 处理ef
if (nums.empty()) {
res += s[i];
} else
letters.push(s[i]);
} if (s[i] >= '0' && s[i] <= '9') {
string tmp = "";
tmp += s[i];
// 处理多个连续的数字
for (int j = i + 1; j < s.length(); j++) {
if (s[j] >= '0' && s[j] <= '9') {
tmp += s[j];
i++;
}
else
break;
} stringstream ss;
ss << tmp;
int value;
ss >> value;
nums.push(value);
}
if (s[i] == ']') {
int value = nums.top();
nums.pop();
string tmp = "";
while (1) {
char c = letters.top();
if (c != '[')
tmp += c;
letters.pop();
if (c == '[')
break;
}
reverse(tmp.begin(), tmp.end());
string tmp2 = "";
for (int i = 0; i < value; i++) {
tmp2 += tmp;
}
// 如果为空了,就直接累加到结果里,否则压入栈中
if (nums.empty()) {
res += tmp2;
} else {
for (int i = 0; i < tmp2.length(); i++)
letters.push(tmp2[i]);
}
}
}
return res;
}
stack<int> nums;
stack<char> letters;
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,083
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,558
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,407
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,180
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,817
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,900