leetcode394:字符串解码

题目链接

leetcode

题目描述

给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a2[4] 的输入。

C++ 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <string>
#include <stack>
#include <vector>
using namespace std;

/*
把字母、数字和括号作为独立的 TOKEN,用栈来维护这些 TOKEN。
注意:可能出现括号嵌套的情况。

具体做法:遍历这个栈
若当前字符为数字,则拼接出完整的数字;
若当前字符为字母,则拼接出完整的字符串;
若当前字符为左括号,则数字和字母都进栈;
若当前字符为右括号,则字母和数字都出栈,根据字符串和次数拼接出新的字符串。
重复如上操作,将栈中的元素按照从栈底到栈顶的顺序拼接,得到答案。

时间复杂度:O(n)
假设解码后的字符串长度为 n,除了遍历一次原字符串 s,
将解码后的字符串中的每个字符都入栈,最终拼接进答案,
时间复杂度为 O(n)。
空间复杂度:O(n)
栈维护 TOKEN,栈的大小等于字符串长度,空间复杂度为 O(n)。
*/
class Solution {
public:
string decodeString(string s) {
string num = "", sign = "";
stack<string> stk;

for (const char& c : s) {
if (isdigit(c)) {
num += c;
} else if (isalpha(c)) {
sign += c;
} else if (c == '[') {
stk.push(num);
stk.push(sign);
num = "";
sign = "";
} else if (c == ']') {
string letters = stk.top(); stk.pop();
string times = stk.top(); stk.pop();
int iTimes = atoi(times.c_str());
for (int i = 0; i < iTimes; i++) {
letters += sign;
}
sign = letters;
}
}

return sign;
}
};

/*
思路同上
*/
class Solution_1 {
public:
string decodeString(string s) {
stack<pair<string, int>> stk;
string str = "";
int num = 0;

for (const char& c : s) {
if (isdigit(c)) {
num = num * 10 + (c - '0');
} else if (isalpha(c)) {
str += c;
} else if (c == '[') {
stk.push({str, num});
str = "";
num = 0;
} else if (c == ']') {
auto top = stk.top(); stk.pop();
string repeatString;
for (int i = 0; i < top.second; i++) {
repeatString += str;
}
str = top.first + repeatString;
}
}

return str;
}
};

int main() {
Solution solution;
vector<string> s_cases = {
"3[a]2[bc]",
"3[a2[c]]",
"2[abc]3[cd]ef",
"abc3[cd]xyz"
};

for (int i = 0; i < s_cases.size(); i++) {
string s = s_cases[i];
string result = solution.decodeString(s);

cout << "Input: s = " << "\"" << s << "\"" << endl;
cout << "Output: " << "\"" << result << "\"" << endl;
}

return 0;
}

leetcode394:字符串解码
https://lcf163.github.io/2024/05/18/leetcode394:字符串解码/
作者
乘风的小站
发布于
2024年5月18日
许可协议