[leetcode]394. Decode String

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

读错题……放弃治疗了以为第一个要输出bbcc来着

发现自己写一个dfs真优雅啊

class Solution {
public:
    string dfs(string s,int &k)
    {
        int tot=0;
        string ans;
        while(k<s.size())
        {
            if(isdigit(s[k]))
                tot=tot*10+s[k++]-'0';
            else if(s[k]=='[')
            {
                k++;
                string tmp=dfs(s,k);
                for(int i=0;i<tot;i++) ans+=tmp;
                tot=0;
            }
            else if(s[k]==']')
            {
                k++;
                return ans;
            }
            else
            {
                ans+=s[k++];
            }
        }
        return ans;
    }
    string decodeString(string s) {
       int k=0;
        return dfs(s,k);
    }
};




猜你喜欢

转载自blog.csdn.net/zhou_yujia/article/details/79545735
今日推荐