LeetCode20. 有效的括号
自己实现
class Solution {
public:
bool isValid(string s) {
if(s.size() % 2) return false;
unordered_map<char, char>hash;
hash['('] = ')';
hash['['] = ']';
hash['{'] = '}';
stack<char> sta;
for(int i = 0; i < s.size(); i++) {
if(hash[s[i]]) {
sta.push(s[i]);
}else if(!sta.empty()) {
char temp = sta.top();
sta.pop();
if(hash[temp] != s[i]) return false;
}else return false;
}
if(sta.empty()) return true;
return false;
}
};
题解
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') st.push(')');
else if (s[i] == '{') st.push('}');
else if (s[i] == '[') st.push(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != s[i]) return false;
else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
总结
LeetCode1047. 删除字符串中的所有相邻重复项
题解
####栈
class Solution {
public:
string removeDuplicates(string s) {
stack<char> sta;
string res = "";
for(char c : s) {
if(sta.empty() || sta.top() != c){
sta.push(c);
}else{
sta.pop();
}
}
while(!sta.empty()) {
res += sta.top();
sta.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
####数组
class Solution {
public:
string removeDuplicates(string s) {
string res = "";
for(char c : s) {
if(res == "" || res.back() != c){
res.push_back(c);
}else {
res.pop_back();
}
}
return res;
}
};
总结
- 题目理解错了,只删除相邻的两个就行,以为要都删掉
- 好像也可以用双指针算法原地删
LeetCode150. 逆波兰表达式求值
题解
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for(int i = 0; i < tokens.size(); i++) {
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
long long a = st.top();
st.pop();
long long b = st.top();
st.pop();
if(tokens[i] == "+") a = b + a;
else if(tokens[i] == "-") a = b - a;
else if(tokens[i] == "*") a = b * a;
else if(tokens[i] == "/") a = b / a;
st.push(a);
}else {
st.push(stoll(tokens[i]));
}
}
return st.top();
}
};
总结
- C++不是很熟练 总是在
string
、char
和int
的地方出现问题 stoll
将string
转换为long long int
类型stol
将string
转换为long long
类型