Decode String

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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".

给定一个编码字符串,返回它的解码字符串。

编码规则是:k [encoded_string],其中方括号内的encoded_string正在重复k次。 注意,k保证是正整数。

您可以假设输入字符串始终有效; 没有多余的空白区域,方括号格式正确等。

此外,您可以假设原始数据不包含任何数字,并且该数字仅用于那些重复数字k。 例如,不会有像3a或2 [4]这样的输入。

2,题目思路

对于这道题,题目是给定一个字符串,字符串是一系列的单词的编码形式,有点类似于数字图像处理里面的编码形式(具体叫什么我也忘了。。)

对于这道题,具体操作起来不是很难,只需要在遍历的过程中对字符进行遍历并具体判断即可。

当遇到数字时,还需要注意数字可能会大于10,因此需要逐步判断。

而单词的判断,通过是否读到’[‘和’]'来判断单词的开始和结束。

另外,通过递归的办法,读取单词,并和之前读取的数字相结合,实现连续几个单词的累加。

3,代码实现

static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();


class Solution {
public:
    string decodeString(string s) {
        int index = 0;
        return decodeHelper(s, index);
        }
private:
    string decodeHelper(string &s, int &i){
        string res = "";
        while(i<s.size() && s[i] != ']'){
            if(!isdigit(s[i]))
                res += s[i++];
            else{
                int wordNum = 0;
                while(i < s.size() && isdigit(s[i]))
                    wordNum = wordNum*10 + (s[i++] - '0');
                i++;    //跳过'['
                string tmp = decodeHelper(s, i);//开启递归,获得括号内的字符串
                i++;    //跳过']'
                
                while(wordNum-- > 0)
                    res += tmp;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值