您的位置:首页 > 编程语言

编程练习(第七周)

2017-04-15 15:08 162 查看


394. Decode String

Add to List

DescriptionHintsSubmissionsSolutions

Total Accepted: 26024
Total Submissions: 63724
Difficulty: Medium
Contributor: LeetCode

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]
.

题解: string decodeString(string s) {
stack<string> chars;
stack<int> nums;
string res;
int num = 0;
for(char c : s) {
if(isdigit(c)) {
num = num*10 + (c-'0');
}
else if(isalpha(c)) {
res.push_back(c);
}
else if(c == '[') {
chars.push(res);
nums.push(num);
res = "";
num = 0;
}
else if(c == ']') {
string tmp = res;
for(int i = 0; i < nums.top()-1; ++i) {
res += tmp;
}
res = chars.top() + res;
chars.pop(); nums.pop();
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: