力扣 394 字符串解码

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

编码规则为: 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".
在真实的面试中遇到过这道题?

思路:
准备两个栈,一个存放数字nums,一个存放字符串strs;准备一个num记录当前次数,准备res记录当前字符串.
遇到‘[’开始入栈,每次入栈更新num和res
遇到‘]’开始弹栈,每次弹栈更新res,使用string temp辅助记录栈顶元素。

主要是弹栈的时候 使用临时变量存放,同时更新res;

#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_map>

using namespace std;

class Solution {
private:
	stack<int> nums;
	stack<string> strs;
public:
	string decodeString(string s) {
		int num = 0;//记录次数
		string res = "";
		for (int i = 0; i < s.size(); ++i) {
			if (s[i] >= '0'&&s[i] <= '9') {
				num = 10 * num + s[i] - '0';
			}
			else if (s[i] >= 'a'&&s[i] <= 'z'||s[i]>='A'&&s[i]<='Z') {
				res += s[i];//记录字符
			}
			else if (s[i] == '[') {//遇到'['将出现次数和字符串入栈
				nums.push(num);
				strs.push(res);//将res存入栈中
				num = 0;
				res = "";
			}
			else if(s[i] == ']') {
				int times = nums.top();
				nums.pop();
				string temp_str = strs.top();
				strs.pop();
				for (int j = 0; j < times; ++j)
					temp_str += res; //每次使用res更新strs.top()然后拿出来给res,然后弹出
				res = temp_str; //更新res
			}
		}
		return res;
	}
};
int main() {
	Solution* ptr = new Solution();
	string res = ptr->decodeString("3[a]2[bc2[af]]");
	cout << res << endl;
	while (1);
}
发布了107 篇原创文章 · 获赞 125 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/Li_haiyu/article/details/100624112