假设我们有一个编码字符串;我们必须返回其解码后的字符串。编码规则为:k [encoded_string],这表示方括号内的encode_string精确地重复了k次。我们可以假定原始数据不包含任何数字字符,并且数字仅用于那些重复的数字k。因此,如果输入像“ 1 [ba] 2 [na]”,那么输出将是“香蕉”。
为了解决这个问题,我们将遵循以下步骤-
创建一个空堆栈,设置i:= 0
而我<一个字符串的大小
res:=从堆栈中删除元素,仅使用方括号内的字符串。
n:= 0
当堆栈不为空,并且堆栈顶部是一个数字字符时,则容纳数字并形成实际整数为n
对于1到n范围内的j
将res [x]插入堆栈
对于x范围从0到res的大小
如果s [i]是']'
否则将s [i]插入堆栈
使我增加1
ans:=一个空字符串
当堆栈不为空时
ans:=堆栈顶部元素+ ans
从堆栈弹出
返回ans
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; class Solution { public: string decodeString(string s) { stack <char> st; int i = 0; while(i<s.size()){ if(s[i] == ']'){ string res = ""; while(st.top()!='['){ res = st.top() + res; st.pop(); } st.pop(); int n = 0; int x = 1; while(!st.empty() && st.top()>='0' && st.top()<='9'){ n = n + (st.top()-'0')*x; x*=10; st.pop(); } for(int j = 1; j <= n; j++){ for(int x = 0; x < res.size();x++){ st.push(res[x]); } } } else{ st.push(s[i]); } i++; } string ans =""; while(!st.empty()){ ans = st.top() + ans; st.pop(); } return ans; } }; main(){ Solution ob; cout << ob.decodeString("1[ba]2[na]"); }
"1[ba]2[na]"
输出结果
"banana"