题解 | #字符串解码#
字符串解码
https://www.nowcoder.com/practice/4e008fd863bb4681b54fb438bb859b92
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
string decodeString(string s) {
// write code here
std::stack<int> multis;
std::string res;
std::string tmp;
int multi = 0;
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
multi = multi * 10 + s[i] - '0';
} else if (s[i] == '[') {
multis.push(multi);
tmp.push_back(s[i]);
multi = 0;
}
else if (s[i] == ']') {
int idx = tmp.find_last_of("[");
std::string core = tmp.substr(idx + 1);
std::string prefix = tmp.substr(0, idx);
int k = multis.top();
multis.pop();
std::string ss;
for (int i = 0; i < k; i++) {
ss += core;
}
prefix += ss;
tmp = prefix;
} else {
tmp.push_back(s[i]);
}
}
return tmp;
}
};

查看12道真题和解析