LeetCode-394. Decode String

本文深入探讨了解码字符串问题的C++解决方案,包括两种算法:一种使用堆栈实现,另一种采用递归方法。详细分析了每种算法的工作原理、代码实现以及时间复杂度,并对比了它们的优劣。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Example

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

Solution 1(C++)

class Solution {
public:
    string decodeString(string s) {
        using P = pair<int,string>; 
        stack<P> st;                        // stack stores pair of {k,encoded_string}
        int k = 0;                          // k-value
        string res = "";                    // result
        for (const auto& c: s) {
            if (isdigit(c))             // if char is digit, then evaluate k-value
                k = k * 10 + c - '0';
            else if (c == '[') {          // push k, and a placeholder string on stack
                st.push({k,""});
                k = 0;          
            } else if (c == ']') {                  // found ']', get stack top element
                P top = st.top(); st.pop();
                while (top.first-- > 0) {
                    if (st.empty())              // stack empty means, '[' ']' non-nested case, so add to result directly
                        res += top.second;
                    else 
                        st.top().second += top.second;   // nested case, so append to next stack entry
                }
            } else {
                if (!st.empty())    
                    st.top().second += c;
                else
                    res += c;                   // 2[abc]3[cd]ef: to handle non-encoded chars (ef), add to result directly 
            }
        }

        while(!st.empty()) {                // populate result if stack not empty (nested case)
            P top = st.top(); st.pop();
            while (top.first-- > 0)
                res += top.second;
        }
        return res;
    }
};

Solution 2(C++)

class Solution {
public:
    string decodeString(string s) {
        int index = 0;
        return helper(s, index);
    }

private:
    string helper(string s, int& index){
        string res;

        while(index < s.size() && s[index] != ']'){
            if(!isdigit(s[index])){
                res += s[index++];
            }
            else{
                int times = 0;
                while(isdigit(s[index])){
                    times = times*10 + (s[index++]-'0');
                }

                index++;
                string temp = helper(s, index);
                index++;

                while(times-- > 0){
                    res += temp;
                }
            }
        }

        return res;
    }
};

算法分析

这道题要说的很详细也没有必要,主要还是编程能力的体现,第一遍我是没做出来。学习这道题的解法推荐解法二,简单易懂,利用了递归的解法。

程序分析

略。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值