20. 有效的括号
文档讲解:代码随想录.有效的括号
视频讲解:栈的拿手好戏!| LeetCode:20. 有效的括号
状态:已完成
代码实现
class Solution {
public:
bool isValid(string s) {
stack<char>s_temp;
if(s.size()%2 !=0){//奇数个,肯定不匹配
return false;
}
for(int i = 0 ; i < s.size();i++){
if(s[i]== '['){
s_temp.push(']');
}else if(s[i]=='{'){
s_temp.push('}');
}else if(s[i]=='('){
s_temp.push(')');
}else if(s_temp.empty()|| s_temp.top() != s[i]){
return false;
}else{
s_temp.pop();
}
}
return s_temp.empty();
}
};
心得记录:
- 做题时还是要认真,总是在细节的地方容易出错
- 在算法中止的地方需要注意。
1047. 删除字符串中的所有相邻重复项
文档讲解:代码随想录.删除字符串中的所有相邻重复项
视频讲解:栈的好戏还要继续!| LeetCode:1047. 删除字符串中的所有相邻重复项
状态:已完成
代码实现
class Solution {
public:
string removeDuplicates(string s) {
stack<char> s_temp;
for (int i = 0; i < s.size(); i++) {
if (!s_temp.empty() && s_temp.top() == s[i]) {
cout << "the top 11 is " << s_temp.top() << endl;
s_temp.pop();
} else {
s_temp.push(s[i]);
cout << "the top 22 is " << s_temp.top() << endl;
}
}
// 读取栈中的元素到字符串
int n = s_temp.size();
string result = "";
for (int i = 0; i < n; i++) {//需要注意栈的长队会改变
result.push_back(s_temp.top());
s_temp.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
心得记录:
- 在对栈进行操作之前,需要检查是否为空
- 遍历的时候需要注意,栈的长度会改变
- pop_back( )移除末尾的字符
150. 逆波兰表达式求值
文档讲解:代码随想录.逆波兰表达式求值
视频讲解:栈的最后表演! | LeetCode:150. 逆波兰表达式求值
状态:已完成
代码实现
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> tokens_temp;
int num_1 = 0;
int num_2 = 0;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" ||
tokens[i] == "/") {
// tokens_temp.push(tokens[i]);
num_1 = tokens_temp.top();
tokens_temp.pop();
num_2 = tokens_temp.top();
tokens_temp.pop();
int num_temp = 0;
if (tokens[i] == "+") {
num_temp = num_2 + num_1 ;
}
if (tokens[i] == "-") {
num_temp = num_2 - num_1;
}
if (tokens[i] == "*") {
num_temp = num_2 * num_1;
}
if (tokens[i] == "/") {
num_temp = num_2 / num_1;
}
tokens_temp.push(num_temp);
// cout << "tokens_temp top 11 is " << tokens_temp.top() << endl;
} else {
tokens_temp.push(
stoll(tokens[i])); // stoll()将字符串转成long long
// cout << "tokens_temp top 22 is " << tokens_temp.top() << endl;
}
}
int result = tokens_temp.top();
tokens_temp.pop();
return result;
}
};
心得记录:
- 做题时还是要仔细审题