【题目】
- Total Accepted: 10087
- Total Submissions: 25510
- Difficulty: Medium
- Contributors: Admin
Given an encoded string, return it's decoded 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.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a
or 2[4]
.
Examples:
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) {
stack<string> strs;
stack<int> counts;
string result = "";
int cnt = ;
for (int i = ; i < s.size(); i++) {
if(s[i] <= '' && s[i] >= '') {
cnt = cnt* + s[i] - '';
cout << "number = " << cnt << endl;
} else if (s[i] == '[') {
cout << "[" << endl;
counts.push(cnt);
strs.push(result);
result.clear();
cnt = ;
} else if (s[i] == ']') {
int cur_cnt = counts.top();
cout << "]" << " cur_cnt = " << cur_cnt << endl;
counts.pop();
for (int j = ; j < cur_cnt; j++) {
strs.top() += result;
}
result = strs.top();
strs.pop();
} else {
result += s[i];
cout << "result += " << s[i] << endl;
}
}
return strs.empty()? result:strs.top();
}
};
注意:
'['后记得要清空result,初始化cnt为0。