码蹄集丨字符串的解码
字符串 解码
2023-09-11 14:16:29 时间
Python代码实现:
原文链接:https://blog.51cto.com/u_15745546/5950626
def main():
s = input()
n = len(s)
arr = []
mm = {}
for i in range(n):
if s[i] == '[':
arr.append(i)
elif s[i] == ']':
mm[arr[-1]] = i
arr.pop(-1)
def decode(ii, jj):
if ii > jj:
return ""
if ii == jj:
return s[ii]
if s[ii] == '[':
x = ii + 1
while x + 1 < jj and '0' <= s[x + 1] <= '9':
x += 1
k = int(s[ii + 1: x + 1])
return decode(x + 1, mm[ii] - 1) * k + decode(mm[ii] + 1, jj)
else:
x = ii
while x + 1 <= jj and s[x + 1] not in "[]":
x += 1
return s[ii: x + 1] + decode(x + 1, jj)
print(decode(0, n - 1))
if __name__ == '__main__':
main();
C++代码实现:
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
string decode(string s, int ii, int jj, unordered_map<int, int>& mm) {
if (ii > jj) {
return "";
}
if (ii == jj) {
return string(1, s[ii]);
}
if (s[ii] == '[') {
int x = ii + 1;
while (x + 1 < jj && s[x + 1] >= '0' && s[x + 1] <= '9') {
x++;
}
int k = stoi(s.substr(ii + 1, x - ii));
string sub_str = decode(s, x + 1, mm[ii] - 1, mm);
string res = "";
for (int i = 0; i < k; i++) {
res += sub_str;
}
return res + decode(s, mm[ii] + 1, jj, mm);
} else {
int x = ii;
while (x + 1 <= jj && s[x + 1] != '[' && s[x + 1] != ']') {
x++;
}
return s.substr(ii, x - ii + 1) + decode(s, x + 1, jj, mm);
}
}
int main() {
string s;
cin >> s;
int n = s.length();
vector<int> arr;
unordered_map<int, int> mm;
for (int i = 0; i < n; i++) {
if (s[i] == '[') {
arr.push_back(i);
} else if (s[i] == ']') {
mm[arr.back()] = i;
arr.pop_back();
}
}
cout << decode(s, 0, n - 1, mm) << endl;
return 0;
}
提交测试结果:
相关文章
- python字符串
- Go 字符串使用
- [Android Security] APK自我保护 - 字符串处理
- 第一百零八节,JavaScript,内置对象,Global对象字符串编码解码,Math对象数学公式
- (算法)判断字符串中是否包含HelloWorld
- JavaScript escape() unescape() decodeURI()函数对字符串进行编码解码
- asp程序里,如何判断一个字符串中存在包含了另一个字符串?
- linux中shell截取字符串方法总结
- C# 字符串的不可变性
- 报错"ORA-01861: 文字与格式字符串不匹配"
- 1375. 二进制字符串前缀一致的次数-前序遍历法
- Python: translate()审查清理文本字符串
- Redis源码之SDS简单动态字符串
- 007-TreeMap、Map和Bean互转、BeanUtils.copyProperties(A,B)拷贝、URL编码解码、字符串补齐,随机字母数字串
- python处理带有‘x‘的字符串,拆分,解码,重组