Loading

LeetCode 394. 字符串解码

 

思路

方法:用栈模拟

 1 class Solution {
 2 public:
 3     string decodeString(string s) {
 4         deque<char> d;
 5 
 6         for(int i = 0; i < s.length(); ++i) {
 7             if(s[i] == ']') {
 8                 deque<char> tmp;
 9                 while(d.back() != '[') {
10                     tmp.push_front(d.back());
11                     d.pop_back();
12                 }
13 
14                 d.pop_back();  //左括号'['出栈
15                 //获取循环次数repeat,注意repeat可能大于1位数
16                 int repeat = 0, r = 1;
17                 while(!d.empty() && isdigit(d.back())) {
18                     repeat += r * (d.back() - '0');
19                     r *= 10;
20                     d.pop_back();
21                 }
22                 
23                 while(repeat--) {
24                     for(int j = 0; j < tmp.size(); ++j) {
25                         d.push_back(tmp[j]);
26                     }
27                 }
28             } else {
29                 d.push_back(s[i]);
30             } 
31         }
32 
33         string res(d.begin(), d.end());
34 
35         return res;
36     }
37 };

复杂度分析:

时间复杂度:O(S),S为答案字符串的长度

空间复杂度:O(S)

posted @ 2021-03-13 20:04  拾月凄辰  阅读(42)  评论(0编辑  收藏  举报