1 条题解
-
1
解题思路
- 括号匹配
- 递归解码
括号匹配
使用栈原理,当遇到"["时当前索引入栈,当遇到"]"时用map以栈顶的"["索引为键(Key),"]"的索引为值(Value)记录,由此可以获得每一个左括号对应的右括号位置。
递归解码
decode函数传入要处理的未解码的字符串的区间,每当找到在该范围内索引i在map表中有记录时(遇到括号)则进行递归调用,进入下一层解码,若没有遇到括号,则正常记录一位字符
特别注意:重复次数可能不止个位数
#include <iostream> #include <cstring> #include <stack> #include <vector> #include <map> using namespace std; map<int, int> kuohao; // 保存括号每组括号对应的位置 stack<int> stk; // 用栈处理括号匹配 string code; string decode(int lIndex, int rIndex) { string str = ""; for (int i = lIndex; i <= rIndex; i++) { if (kuohao[i] != 0) { // 读取重复次数(可能多位数) int j = i + 1; int times = 0; while (j <= rIndex && isdigit(code[j])) { times = times * 10 + (code[j] - '0'); j++; } string repeat = decode(j, kuohao[i]); // 递归调用获取括号中的字符 for (int k = 1; k <= times; k++) { str.append(repeat); // 按照次数重复添加 } i = kuohao[i]; // 跳转到括号后面的字符 } else if (code[i] != ']') { str.push_back(code[i]); // 非括号非数字的字符正常记录 } } return str; } int main() { cin >> code; // 匹配括号 for (int i = 0; i < code.size(); i++) { if (code[i] == '[') { stk.push(i); } else if (code[i] == ']') { kuohao[stk.top()] = i; stk.pop(); } } cout << decode(0, code.size() - 1) << endl; return 0; }
- 1
信息
- ID
- 168
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 8
- 标签
- 递交数
- 185
- 已通过
- 33
- 上传者