394. Decode String
Given an encoded string, return it’s 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:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
方法1: 2 stacks
思路:
用两个栈来存储数字和字符串。如果遇到数字,就持续累计。如果遇到"["将当前累计好的字符推荐st_str,将成为prefix。如果遇到“]”,需要从st_num找出需要repeat多少次,执行完毕后加好prefix,继续前进。注意此时不会将current清零,也不会做推栈。
易错点
- repeat的时候不要用current += current:会以1,2,4,8 这样加倍。。
- 只有“[”才会推栈。
Complexity
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
string decodeString(string s) {
stack<int> st_num;
stack<string> st_str;
string result = "", current = "";
int num = 0;
for (char c: s){
if (isdigit(c)) {
num = num * 10 + c - '0';
}
else if (c == '[') {
st_num.push(num);
st_str.push(current);
num = 0;
current = "";
}
else if (c == ']') {
int num = st_num.top();
st_num.pop();
string prefix = st_str.top();
st_str.pop();
string tmp = "";
for (int i = 0; i < num; i++) {
tmp += current;
}
current = prefix + tmp;
} else {
current += c;
}
}
return current;
}
};
方法2: recursion
思路
把每对括号看作一个decode的整体,在每次“[”之后调用递归,return的是整体解码之后(包括重复)的字串,和之前的字符连接后返回。
class Solution {
public:
string decodeString(string s) {
int i = 0;
return helper(s ,i);
}
string helper(string s, int& i){
string current;
while(i<s.size() && s[i]!=']'){
if(!isdigit(s[i])) current+=s[i++];
else{
int num = 0;
while(i<s.size() && isdigit(s[i])) num = num * 10 + s[i++] - '0';
i++;
string t = helper(s, i);
i++;
while(num-->0) current+=t;
}
}
return current;
}
};
while (num – > 0) 就不行?????
class Solution {
public:
string decodeString(string s) {
int i = 0;
return helper(s, i);
}
string helper(string s, int & i) {
int num = 0;
string tmp;
for (; i < s.size(); i++) {
if (s[i] == '[') {
string segment = helper(s, ++i);
// while (num-- > 0) {
for (; num > 0; num--){
tmp += segment;
}
}
else if (isdigit(s[i])) {
num = num * 10 + s[i] - '0';
}
else if (s[i] == ']') {
return tmp;
}
else if (isalpha(s[i])) {
tmp += s[i];
}
}
return tmp;
}
};