問題描述:
給定一個經過編碼的字符串,返回它解碼後的字符串。
編碼規則爲: k[encoded_string],表示其中方括號內部的 encoded_string 正好重複 k 次。注意 k 保證爲正整數。
你可以認爲輸入字符串總是有效的;輸入字符串中沒有額外的空格,且輸入的方括號總是符合格式要求的。
此外,你可以認爲原始數據不包含數字,所有的數字只表示重複的次數 k ,例如不會出現像 3a 或 2[4] 的輸入。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/decode-string
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
解題思路:
使用棧,開闢一個int型棧和string棧
使用變量num和str,
當遇到'['字符時,將num壓入int棧,同時num重置0
遇到']'字符時,取出num棧頂元素k,tempstr = k*str; string棧頂元素變爲 top()+tempstr
完整代碼如下:
class Solution {
public:
string decodeString(string s) {
int len = s.size();
int num = 0;
stack<int> numstack;
stack<string> strstack;
string cur ="";
string res ="";
for(int i=0;i<len;i++){
if(s[i]>='0' && s[i]<='9'){
num = 10*num+s[i]-'0';
}
else if(s[i]=='['){
numstack.push(num);
strstack.push(cur);
num = 0;
cur.clear();
}
else if((s[i]>='A'&& s[i]<='Z')||(s[i]>='a'&&s[i]<='z')){
cur+=s[i];
}
else if(s[i]==']'){
int k = numstack.top();
numstack.pop();
string temp ="";
for(int j=0;j<k;j++){
temp +=cur;
}
string str = strstack.top();
cur = str+temp;
strstack.pop();
}
}
res = cur;
return res;
}
};