今天的三个题之前都做过,全部是栈的应用,都很简单~
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (st.empty()) {
if (s[i] == ')' || s[i] == '}' || s[i] == ']')
return false;
}
if (s[i] == '(' || s[i] == '{' || s[i] == '[') st.push(s[i]);
if (s[i] == ')') {
if (st.top() == '(') st.pop();
else st.push(s[i]);
}
if (s[i] == '}') {
if (st.top() == '{') st.pop();
else st.push(s[i]);
}
if (s[i] == ']') {
if (st.top() == '[') st.pop();
else st.push(s[i]);
}
}
if (st.empty()) return true;
else return false;
}
};
最后需要把stack的char字符汇总为一个string
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (st.empty()) st.push(s[i]);
else {
if (st.top() == s[i]) st.pop();
else st.push(s[i]);
}
}
string result = "";
while (!st.empty()) { // 将栈中元素放到result字符串汇总
result += st.top();
st.pop();
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};
经典栈的应用
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 num1 = st.top();
st.pop();
long long 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(stoll(tokens[i]));
}
}
int result = st.top();
return result;
}
};