题解 | #牛牛的字符串解码问题#
牛牛的字符串解码问题
https://www.nowcoder.com/practice/e5658311e6d44b74872e843ba13ee290
#include <cctype>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
string decodeString(string s)
{
// write code here
string ans;
int i = 0;
while (i < s.length()) {
if (isalpha(s[i])) {
ans += s[i];
i++;
} else if (isdigit(s[i])) {
int repeat = 0;
while (isdigit(s[i])) {
repeat = repeat * 10 + (s[i] - '0');
i++;
}
i++; // skip '['
int start = i;
int count = 1;
while (count > 0) {
i++;
if (s[i] == '[') count++;
else if (s[i] == ']') count--;
}
string repeatedStr = decodeString(s.substr(start, i - start));
for (int j = 0; j < repeat; j++) {
ans += repeatedStr;
}
i++; // skip ']'
}
}
return ans;
}
};
查看10道真题和解析