2024每日刷题(131)
Leetcode—394. 字符串解码
实现代码
class Solution {
public:string decodeString(string s) {string curstr;int curNum = 0;stack<pair<string, int>> st; for(char c: s) {if(isdigit(c)) {curNum = curNum * 10 + (c - '0');} else {if(c == '[') {st.emplace(curstr, curNum);curstr = "";curNum = 0;} else if(c == ']') {auto [prestr, num] = st.top();st.pop();curstr = prestr + res(curstr, num);} else {curstr += c;}}}return curstr;}
private:string res(const string& s, int n) {string ans;while(n--) {ans += s;}return ans;}
};
运行结果
递归实现代码
class Solution {
public:string decodeString(string s) {string ans;while(i < s.length() && s[i] != ']') {if(isdigit(s[i])) {int num = 0;while(isdigit(s[i])) {num = num * 10 + s[i] - '0';i++;}i++;string str = decodeString(s);i++;while(num--) {ans += str;}} else {ans += s[i++];}}return ans;}
private:int i = 0;
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!