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'; 

转载于:https://www.cnblogs.com/kykai/p/11588466.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值