题目解析

2[bc]这样格式的字符串变成bcbc,2表示中括号里字符串重复的次数。

方法

主要是字符串的操作,遇到]时再进行操作,取出[abc]里的字符串,同时使用isdigit判断数字来获得重复次数,使用stoi将字符串转换为数字,然后使用str.replace(size_t pos, size_t len, const string & str)来替换解码后的字符串,需要注意的是索引i,再字符串解码后需要变成i+1+newStr.size()

时间复杂度O(N),N是变换后的长度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
string decodeString(string s) {
int i = 0;
while(i != s.size()) {
if (s[i] == ']') {
int end = i;
string cur = "", num = "";
while (s[--i] != '[') cur = s[i] + cur;
i--;
while (i>=0 && isdigit(s[i])) {
num = s[i] + num;
i--;
}
int nums = stoi(num);
string curs = "";
while (nums--) curs += cur;
s.replace(i+1, end-i, curs);
i = i + 1 + curs.size();
} else {
i++;
}
}
return s;
}
};