题目链接
leetcode
题目描述
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string]
,表示其中方括号内部的 encoded_string
正好重复 k
次。注意 k
保证为正整数。
输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,原始数据不包含数字,所有的数字只表示重复的次数 k
,例如不会出现像 3a
或 2[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;
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; }
|