leetcode.394 Decode String

来源:互联网 发布:新日铁住金软件上海 编辑:程序博客网 时间:2024/06/13 03:02

class Solution {

public:

    string decodeString(string s) {

        if(s.size()==0)

            return"";

        stack<char> a;

        for(int i=0;i<=s.size()-1;i++)

        {

            if(s[i]>='0'&&s[i]<='9')

                a.push(s[i]);

            if(s[i]=='[')

                a.push(s[i]);

            if(s[i]>='a'&&s[i]<='z')

                a.push(s[i]);

            if(s[i]==']')

            {

                string str;

                char c=a.top();

                a.pop();

                while(c!='[')

                {

                    str=c+str;

                    c=a.top();

                    a.pop();

                }

                int num=0;

                int l=1;

                while(!a.empty())

                {

                    if(a.top()>='0'&&a.top()<='9')

                    {

                        num=num+l*(a.top()-'0');

                        a.pop();

                        l*=10;

                    }

                    else

                        break;

                }

                string p=str;

                for(int i=1;i<=num-1;i++)

                    str=str+p;

                for(int i=0;i<=str.size()-1;i++)

                    a.push(str[i]);

            }

        }

       string res;

        while(!a.empty())

        {

            res=a.top()+res;

            a.pop();

        }

        return res;

    }

};


原创粉丝点击