Thursday, March 12, 2020

394. Decode String (Memium ) !

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; there are 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 will not be input like 3a or 2[4].

The test cases are generated so that the length of the output will never exceed 105.

 

Example 1:

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

Example 2:

Input: s = "3[a2[c]]"
Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"

 

Constraints:

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

A:

class Solution {
public:
string decodeString(string s) {
string res = "";
int idx = 0;
while (idx < s.size()) {
char ch = s[idx];
if (isalpha(ch)) {
res += ch;
++idx;
} else if (isdigit(ch)) { // get number
int start = idx;
while (idx < s.size() && isdigit(s[idx])) {
++idx;
}
int count = stoi(s.substr(start, idx - start));
// now s[idx] == '['
start = ++idx;
int c = 1;
while (c > 0) {
if (s[idx] == '[') {
++c;
} else if (s[idx] == ']') {
--c;
}
++idx;
}
auto subS = decodeString(s.substr(start, idx - 1 - start));
for (int i = 0; i < count; i++)
res += subS;
} else {
// error
cout << "error at idx " << idx << " " << s << endl;
}
}
return res;
}
};

Mistakes:


1: 一开始没有考虑嵌套的情况

2 : 忘记了 string substr(start, length) 还以为是[start, end) ,哎



No comments:

Post a Comment