Code & Func
2019-11-08

第四天。

今天的题目是Decode String


Given an encoded string, return its 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].

Examples:

1
s = "3[a]2[bc]", return "aaabcbc".
2
s = "3[a2[c]]", return "accaccacc".
3
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

比较简单的一道题,先分析一下题目,首先输入的格式是k[encoded_string],要将其扩展成k 个 encoded_string 组成的字符串,我们暂且先不考虑嵌套的情况,我们通过一个简单的状态机就可以解决这个问题:

default

这个代码写起来也很简单:

1
string decodeString(string s) {
2
string res;
3
string temp;
4
int num = 0;
5
for(int i = 0, size = s.size(); i < size; i++) {
6
if (isdigit(s[i])) {
7
num = num * 10 + s[i] - '0';
8
} else if (s[i] == '[') {
9
res += temp;
10
temp = "";
11
} else if (s[i] == ']') {
12
for(int i = 0;i < num;i++)
13
res += temp;
14
temp = "";
15
} else { // charar
6 collapsed lines
16
temp.push_back(s[i]);
17
num = 0;
18
}
19
}
20
return res;
21
}

如果这道题不需要考虑嵌套问题的话,上面就是正确的答案了。虽然需要处理嵌套的问题,但是其实只需要用栈来模拟多个层次的嵌套即可:

1
string decodeString(string s) {
2
int num = 0;
3
4
stack<string> sst;
5
stack<int> nst;
6
nst.push(1);
7
sst.push(string());
8
9
for(int i = 0, size = s.size(); i < size; i++) {
10
if (isdigit(s[i])) {
11
num = num * 10 + s[i] - '0';
12
} else if (s[i] == '[') {
13
beg = end = i + 1;
14
nst.push(num); num = 0;
15
sst.push(string());
10 collapsed lines
16
} else if (s[i] == ']') {
17
string s = sst.top(); sst.pop();
18
int n = nst.top(); nst.pop();
19
for(int j = 0;j < n;j++) sst.top() += s;
20
} else { // char
21
sst.top().push_back(s[i]);
22
}
23
}
24
return sst.top();
25
}

update at 2020-04-04

似乎最上面那个代码是有问题的,emmm,不管了,更新一个用一个stack的版本:

1
string decodeString1(string s) {
2
stack<pair<int, string>> st;
3
st.push(make_pair(1, ""));
4
int num = 0;
5
for(auto c: s) {
6
if (isdigit(c)) {
7
num = num * 10 + c - '0';
8
} else if (c == '[') {
9
st.push(make_pair(num, ""));
10
num = 0;
11
} else if (c == ']') {
12
auto p = st.top(); st.pop();
13
int n = p.first;
14
auto s = p.second;
15
// cout << n << s << endl;
7 collapsed lines
16
for(int i = 0; i < n; i++) st.top().second += s;
17
} else {
18
st.top().second.push_back(c);
19
}
20
}
21
return st.top().second;
22
}
上一条动态