题解 | #牛牛的字符串解码问题#
牛牛的字符串解码问题
https://www.nowcoder.com/practice/e5658311e6d44b74872e843ba13ee290
递归
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串 */ pair<string, int> convertString(string s, int i) { string ret = ""; string num = ""; num += s[i]; string substr = ""; int idx = 0; for (int j = i + 1; j < s.length(); j++) { if (s[j] <= '9' && s[j] >= '0') num += s[j]; else if (s[j] == '[') { for (int k = j + 1; k < s.length(); k++) { if (s[k] >= 'a' && s[k] <= 'z') substr += s[k]; else if (s[k] == ']') { idx = k; break; } else if (s[k]>='1'&&s[k]<='9'){ auto p = convertString(s, k); substr+=p.first; k = p.second; } } break; } } int time = atoi(num.c_str()); for (int i = 0; i < time; i++) { ret += substr; } return {ret, idx}; } string decodeString(string s) { // write code here string ret = ""; for (int i = 0; i < s.length(); i++) { if (s[i] >= 'a' && s[i] <= 'z') ret += s[i]; if (s[i] >= '1' && s[i] <= '9') { auto p = convertString(s, i); ret += p.first; i = p.second; } } return ret; } };