394. Decode String 题解

394. Decode String题解


题目描述:

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

题目链接:394. Decode String


算法描述:


根据题意,给出一串带有数字和字母的 “编码” 字符串,我们将对它进行 “解码” ,返回 “解码” 后的字符串。“解码” 的方式见题目描述。


我们用两个栈来实现它,栈 num 存储原字符串的数字, 栈 str 存储原字符串的字母。我们对原字符串的进行遍历,当遍历到字母时,将该字母放进栈 str 中;当遍历到 “[” 时,进行准备操作,具体的操作见下面的代码;当遍历到字母时,将字母赋予字符串 ans ;当遍历到 “]” 时构造子结果:从栈中取出 num 存储的数字,构造此次子结果 ans,从 str 中取出之前已经构造好的子结果,并将其与 ans 连接,新构造好的 ans 为新的子结果。遍历完成之后返回ans。


代码:

class Solution {
public:
    string decodeString(string s) {
        stack<int> num;
        stack<string> str;
        string ans;
        int i=0;
        
        while(i<s.length()){
            if(s[i]<='9' && s[i]>='0'){
                int count=0;
                while(s[i]<='9' && s[i]>='0'){
                    count=count*10 + (s[i]-'0');
                    i++;
                }
                num.push(count);
            }
            else if(s[i]=='['){
                str.push(ans);
                ans="";
                i++;
            }
            else if(s[i]==']'){
                string temp=str.top();
                str.pop();
                int clic= num.top();
                num.pop();
                for(int j=0; j<clic; j++){
                    temp+=ans;
                }
                ans=temp;
                i++;
            }
            else{
                ans+=s[i];
                i++;
            }
        }
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值