题目介绍
题目描述
- 为了提升数据传输的效率,会对传输的报文进行压缩处理。
- 输入一个压缩后的报文,请返回它解压后的原始报文。
- 压缩规则:n[str],表示方括号内部的 str 正好重复 n 次。
- 注意 n 为正整数(0 < n <= 100),str只包含小写英文字母,不考虑异常情况。
输入描述:
输入压缩后的报文:
1)不考虑无效的输入,报文没有额外的空格,方括号总是符合格式要求的;
2)原始报文不包含数字,所有的数字只表示重复的次数 n ,例如不会出现像 5b 或 3[8] 的输入;
输出描述:
解压后的原始报文
注:
1)原始报文长度不会超过1000,不考虑异常的情况
示例 1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
3[k]2[mn]
输出
kkkmnmn
说明
k 重复3次,mn 重复2次,最终得到 kkkmnmn
示例2 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
3[m2[c]]
输出
mccmccmcc
说明
m2[c] 解压缩后为 mcc,重复三次为 mccmccmcc
题目解答
解题思路
这个题目更像是模拟类型的题目,思路很简单,题目怎么说,代码怎么写。
3[k]2[mn]
3[m2[c]]
3[m2[c]]4[d]
思路如下,用栈来存储[
的下标,当遇到[
的时候将其下标压入栈,遇到]
的时候就开始操作了。
第一,把前面的数字提取出来,比如2[
中的2。
第二,把前面的字符串提取出来,比如m2[
中的m。
第三,把[]
中间的字符串提取出来,这里要分情况讨论,当是内嵌3[m2[m3[m2[c]]]]
的时候,这个
在最内层的时候,需要自己手动提取,当不是最内层的时候,就要依赖上一层得到的结果。
算法实现
代码实现
#include <limits.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
void getdata(string& frontstr, int& nums, string s, int start) {
int i = 0;
int j = 0;
string tempnum;
for (i = start - 1; i >= 0; i--) {
if (s[i] == ']' || s[i] == '[') {
break;
}
}
for (j = i + 1; j < s.size(); j++) {
if (s[j] < 'a' || s[j] > 'z') {
break;
}
frontstr.push_back(s[j]);
}
for (int l = j; l < s.size(); l++) {
if (s[l] == '[') {
int temp = atoi(tempnum.c_str());
nums = temp;
break;
}
tempnum.push_back(s[l]);
}
}
string minWindow(string s) {
stack<int> st;
string result = "";
string res = "";
for (int i = 0; i < s.size(); i++) {
if (s[i] == '[') {
st.push(i);
continue;
}
if (s[i] == ']') { //遇到]开始操作
int start = st.top();
st.pop();
int end = i;
string frontstr;
int nums;
getdata(frontstr, nums, s, start); //提取[前面的数字,字符串
if (res.empty()) { //如果是最内层,需要手动提取
res = s.substr(start + 1, end - start - 1);
}
string tempres = "";
for (int i = 0; i < nums; i++) {
tempres += res;
}
res = frontstr + tempres;
if (st.empty()) { //栈道为空,说明一个内嵌[]结束,需要将res清空,来迎接下一个内嵌
result += res;
res = "";
}
}
}
return result;
}
};
int main() {
Solution a;
string test;
cin >> test;
cout << a.minWindow(test) << endl;
return 0;
}
运行截图
本文含有隐藏内容,请 开通VIP 后查看