解压报文
标题:解压报文 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
为了提升数据传输的效率,会对传输的报文进行压缩处理。输入一个压缩后的报文,请返回它解压后的原始报文。
压缩规则:n[str],表示方括号内部的 str 正好重复 n 次。注意 n 为正整数(0 < n <= 100),str只包含小写英文字母,不考虑异常情况。
def recur(origin): num, char = '', '' for pos in range(origin, len(s)): if s[pos].isalnum(): num += s[pos] if s[pos] == '[': j = pos + 1 while j < len(s): if s[j].isalpha(): char += s[j] j += 1 elif s[j] == ']': return j +1,char * int(num) elif s[j].isalnum(): new, sub = recur(j) j, char = new, char + sub while True: try: s = input().strip() ans, i = '', 0 while True: if i >= len(s): break i, ret = recur(i) ans += ret print(ans) except: break
def get_ans(s): ans = '' n = len(s) i = 0 while i < n: if s[i].isdigit(): num = 0 while s[i].isdigit(): num = num * 10 + int(s[i]) i += 1 i += 1 tmp = '' while s[i] != ']': if s[i].isdigit(): t = '' cnt = 1 while i < n and cnt > 0: if s[i] == '[': cnt += 1 elif s[i] == ']': cnt -= 1 if cnt > 0: t += s[i] i += 1 tmp += get_ans(t) break else: tmp += s[i] i += 1 for k in range(num): ans += tmp else: ans += s[i] i += 1 return ans s =input() print(get_ans(s)) //160
#include<iostream>
#include<stack>
#include<map>
using namespace std;
map<int, int> mp;
std::string solve(const string &a,int x,int y)
{
if (x > y)
{
return "";
}
std::string ans = "";
int num = 0;
int i = x;
while(1)
{
if (i > y) break;
if (a[i] >= '0' && a[i] <= '9')
{
num = num * 10 + (a[i] - '0');
i++;
}
else if (a[i] == '[')
{
std::string tmp = solve(a, i + 1, mp[i]-1);
for (int i = 0; i < num; i++)
{
ans += tmp;
}
num = 0;
i = mp[i] + 1;
}
else
{
ans = ans + a[i];
num = 0;
i++;
}
}
return ans;
}
int main()
{
string a;
while (cin >> a)
{
int n = a.size();
stack<int> st;
for (int i = 0; i < n; i++)
{
if (a[i] == '[')
{
st.push(i);
}
else if (a[i] == ']')
{
int x =st.top();
st.pop();
mp[x] = i;
}
}
cout << solve(a,0,n-1) << endl;
}
return 0;
}
package main
import (
"fmt"
"strconv"
)
func main() {
var s string
fmt.Scan(&s)
fmt.Println(re(s))
}
func re(str string) string {
left, right := find(str)
if left == 0 {
return str
}
count, p := findCount(str, left)
var tmp string
for i := 0; i != count; i++ {
tmp += str[left+1 : right]
}
res := str[:p] + tmp + str[right+1:]
return re(res)
}
func find(str string) (int, int) {
var left, right int
for i, item := range str {
switch item {
case '[':
left = i
case ']':
right = i
}
if right != 0 {
break
}
}
return left, right
}
func findCount(str string, left int) (int, int) {
var (
tmp string
point int
)
for i := left - 1; i >= 0; i-- {
if str[i] < '0' || str[i] > '9' {
break
}
point = i
tmp = string(str[i]) + tmp
}
res, err := strconv.Atoi(tmp)
if err != nil {
panic(err)
}
return res, point
}

