今日内容:
- 20. 有效的括号
- 考虑三种情况,左括号多了,左右括号不匹配,右括号多了
-
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(); } };
- 1047. 删除字符串中的所有相邻重复项
- 当遍历当前的这个元素的时候,去栈里看一下我们是不是遍历过相同数值的相邻元素。
-
然后再去做对应的消除操作。
-
class Solution { public: string removeDuplicates(string S) { stack<char> st; //遍历字符串中的元素,依次存入栈中,空栈时直接存入,栈中的元素与遍历的元素相同时就消除,不同时存入 for (char s : S) { if (st.empty() || s != st.top()) { st.push(s); } else { st.pop(); // s 与 st.top()相等的情况,消除 } } string result = ""; while (!st.empty()) { // 将栈中元素放到result字符串汇总 result += st.top(); st.pop(); } reverse (result.begin(), result.end()); // 此时字符串需要反转一下 return result; } };
- 150. 逆波兰表达式求值
- 依次遍历元素存入栈中,遇到+-*/四种运算符,即弹出数字,然后进行相应的运算,计算之后再存入栈,最后栈中只剩下一个元素,就是最终的结果。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
} else {
st.push(stoi(tokens[i]));//将字符串类型转换为int型
}
}
int result = st.top();
st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
return result;
}
};