Leetcode 394:字符串解码

    xiaoxiao2022-07-14  142

    题目描述

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

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

    你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

    此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

    示例:

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

     

    解题思路

    class Solution { public: string decodeString(string s) { string fid = "0123456789"; string::size_type st = s.find_last_of(fid); while(st!=string::npos){ string::size_type st1 = s.find_first_of("[",st); string::size_type st2 = s.find_first_of("]",st); while(st>0&&(s[st-1]>='0'&&s[st-1]<='9')) st--; string tmp = s.substr(st1+1,st2-st1-1),t=""; string times = s.substr(st,st1-st); int time = atoi(times.c_str()); for(int i=1;i<=time;i++) t+=tmp; s.replace(st,st2-st+1,t); st = s.find_last_of(fid); } return s; } };
    最新回复(0)