lc20有效的括号
文章&视频:lc20
代码:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (auto c : s) {
// 左括号入栈
if (c == '(' || c == '[' || c == '{') {
stk.push(c);
}
// 右括号出栈
if (c == ')' || c == ']' || c == '}') {
if (stk.empty()) return false;
char top = stk.top();
stk.pop();
if (top == '(' && c == ')') continue;
if (top == '[' && c == ']') continue;
if (top == '{' && c == '}') continue;
else return false;
}
}
return stk.empty();
}
};
lc1074删除字符串中的所有相邻重复项
文章&视频:lc1074
代码:
class Solution {
public:
string removeDuplicates(string s) {
stack<char> stk;
string result = "";
for (auto c : s) {
if (stk.empty()) {
stk.push(c);
}
// 相邻两个字符是重复的,弹出栈顶元素
else {
char top = stk.top();
if (c == top) {
stk.pop();
}
else {
stk.push(c);
}
}
}
while (!stk.empty()) {
result += stk.top();
stk.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
lc150逆波兰数
文章&视频:lc150
代码:老有个错误,喂给GPT说地址没对齐,对于C++的char类型和string类型还是了解不深。