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;
};
运行结果
2024.9.16重温一遍
stack大法
class Solution {
public:
string decodeString(string s) {
string curStr;
stack<pair<string, int>> st;
int curNum = 0;
for(char c: s) {
if(isdigit(c)) {
curNum *= 10;
curNum += c - '0';
} else {
if(c == '[') {
st.emplace(curStr, curNum);
curStr = "";
curNum = 0;
} else if(c == ']') {
auto [preStr, repeats] = st.top();
st.pop();
curStr = preStr + res(curStr, repeats);
} else {
curStr += c;
}
}
}
return curStr;
}
private:
string res(const string& s, int num) {
string ans;
while(num--) {
ans += s;
}
return ans;
}
};
运行结果
2024.10.29重温一遍
stack 实现代码
class Solution {
public:
string repeatNstr(string& s, int n) {
string ans;
while(n--) {
ans += s;
}
return ans;
}
string decodeString(string s) {
string curStr;
stack<pair<string, int>> st;
int curNum = 0;
for(const 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, n] = st.top();
st.pop();
curStr = prestr + repeatNstr(curStr, n);
} else {
curStr += c;
}
}
return curStr;
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!