LC 394. 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:

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

参考答案

 1 class Solution{
 2 public:
 3     string decodeString(string s) {
 4         int pos = 0;
 5         return foo(pos, s);
 6     }
 7     
 8     string foo(int& pos, string s){
 9         int num = 0;
10         string word = "";
11         for(;pos<s.size();++pos){ // 3[ab] = ababab
12             char cur = s[pos];
13             if(cur >='0' && cur <= '9'){
14                 num = num * 10 + cur - '0'; // 计算出倍数
15             }else if(cur == ']'){
16                 return word; // 结束
17             }else if(cur == '['){
18                 string curStr = foo(++pos, s); // 如果遇到 [ ,将 pos 向后移动一位
19                 for(;num>0;num--) word += curStr; // 上一行获得了curStr,而num是上一个循环准备好了,所以可以直接使用。
20             }else{
21                 word += cur; // 这个是为了应对平常的 char -> return curStr
22             }
23         }
24         return word;
25     }
26 };

额外说明

灵魂

这个答案的灵魂,在于当 s[pos] == “[” 的时候,foo( ++pos, s)。

数字,代表×的倍率,一定会出现的。

[ ,代表会出现要处理的字符串,因此这一栏有 string curStr,并且由于有 num 了,所以处理拼合好的字符,也是在这里进行处理的。

],代表着所有递归的结束,不论是大循环,还是小循环,返回 word。

else,也是灵魂,一定意味着normal character,所以直接附在word后面即可。等遇到了 ] ,直接返回,交给 刚才的 ] 里面的 for 处理。

数字,从string到int

int num = 0;

for cur in string:

  num = num * 10 + cur - '0'; 

猜你喜欢

转载自www.cnblogs.com/kykai/p/11588466.html
今日推荐