leetcode 394 Decode String
题意:The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
看例子即可懂。
s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.
class Solution {
public:
string decodeString (string &s, int &i){
int len = s.length();
string res;
int cnt;
while(i < len && s[i] != ']'){
if(isdigit(s[i])){
cnt=0;
while(isdigit(s[i])){
cnt = cnt * 10 + s[i] -'0';
i++;
}
i++;
string tmp = decodeString(s,i);
i++;
while( cnt-- ){
res += tmp;
}
}
else{
res+=s[i];
i++;
}
}
return res;
}
string decodeString(string s) {
int i = 0;
return decodeString(s,i);
}
};