LeetCode 394. 字符串解码(栈)

解码字符串的栈算法
本文介绍了解决LeetCode上解码字符串问题的一种有效方法,使用栈来处理字符串中的数字和字符,通过迭代和条件判断实现字符串的解码,详细解析了算法流程和代码实现。

1. 题目

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

编码规则为: 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".

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 栈解题

class Solution {
public:
    string decodeString(string s) {
        int i, j, n = 0, num;
        string str, temp, ans;
        stack<int> intStk;
        stack<char> charStk;
        for(i = 0; i < s.size(); ++i)
        {
        	if(s[i] >= '0' && s[i] <= '9')
        		n = n*10 + s[i] - '0';//记录整数是啥
        	else if(!(s[i] >= '0' && s[i] <= '9') && s[i] != ']')
        	{
        		if(s[i] == '[')//整数存好了
        		{
        			intStk.push(n);
        			n = 0;//为下次准备好自己
        		}
        		charStk.push(s[i]);
        	}
        	else//s[i] == ']'
        	{
        		num = intStk.top();//取出数字
        		intStk.pop();
        		while(charStk.top() != '[')
        		{
        			temp = charStk.top()+temp;//[]里面是啥呢?temp
        			charStk.pop();
        		}
        		charStk.pop();//'['
        		while(num--)//字符temp*num次
        		{
        			str += temp;
        		}
                for(j = 0; j < str.size(); ++j)//把得到的str入栈
                    charStk.push(str[j]);
        		str = temp = "";//为下次做准备
        	}
        }
        while(!charStk.empty())//取出所有结果
        {
        	ans = charStk.top()+ans;
        	charStk.pop();
        }
        return ans;
    }
};

在这里插入图片描述

LeetCode 394字符串解码问题中,C++递归解决方案的核心在于每次递归要取出数字以及对应括号里的内容,递归完成之后,将其按循环次数添加到结果字符串中。以下是两种不同的C++递归实现代码: 第一种实现方式: ```cpp class Solution { public: string decodeString(string s) { // 题意编码的实现,是递归的过程 int pos = 0; return dfs(s, pos); } // 每次递归要做的事:取出数字,以及对应括号里的内容,递归完成之后,循环次数添加到res中 // 注意点:[ 、]符号的跳过 string dfs(string& s, int& pos) { string res = ""; while (pos < s.size() && s[pos] != ']') { if (isalpha(s[pos])) res += s[pos++]; else if (isdigit(s[pos])) { // 没到数字,就确定完数字向后递归 int cnt = 0; while (isdigit(s[pos])) cnt = cnt * 10 + s[pos++] - '0'; pos++; // 最后一次终止条件在[ , 否则递归时不满足while条件,直接退出 string y = dfs(s, pos); pos++; // pos++用于去除] for (int i = 0; i < cnt; i++) res += y; } } return res; } }; ``` 这种实现方式在`dfs`函数里,利用`while`循环遍历字符串,根据字符是字母还是数字进行不同处理。遇到字母直接添加到结果字符串,遇到数字则先解析出重复次数,递归处理括号内的字符串,最后按次数添加到结果中。 第二种实现方式: ```cpp class Solution { private: int get_digit(string& s, int &index) { int num = 0; while (index < s.length() && isdigit(s[index])) num = num * 10 + s[index++] - '0'; return num; } string get_str(string& s, int &index) { // 递归的出口,前一个很容易想到,后一个作为递归出口的条件,更加方便 if (index >= s.length() || ']' == s[index]) return ""; string str; if (isdigit(s[index])) { // 如果是数字,先获取重复的次数,再获取字符串 int cnt = get_digit(s, index); // 获取重复的次数 index++; // 精髓,跳过'['符号 string temp = get_str(s, index); // 获取下一个字符串 index++; // 精髓,跳过']'符号 while (cnt--) str += temp; // 重复添加字符串 } else { // 如果不是数字,则直接获取字符串 while (isalpha(s[index])) str += s[index++]; } // 返回这一次的结果+后面的结果 return str + get_str(s, index); } public: string decodeString(string s) { int i = 0; return get_str(s, i); } }; ``` 此实现方式通过`get_digit`函数解析重复次数,`get_str`函数进行递归处理。当遇到数字时,先获取重复次数,跳过`[`,递归处理括号内字符串,再跳过`]`,最后按次数添加;遇到字母则直接添加到结果字符串。最终返回当前处理结果与后续递归结果的拼接。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael阿明

如果可以,请点赞留言支持我哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值