题目:20
class Solution {
public:
bool isValid(string s) {
if(s.size()%2!=0) return false;
stackst;
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(‘}’);
}else if(st.empty()||s[i]!=st.top()){
return false;
}else{
st.pop();
}
}
return st.empty();
}
};
题目;1047
class Solution {
public:
string removeDuplicates(string S) {
stack st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
} else {
st.pop(); // s 与 st.top()相等的情况
}
}
string res=“”;
while(!st.empty()){
res+=st.top();
st.pop();
}
reverse (res.begin(),res.end());
return res;
}
};
题目:150
class Solution {
public:
int evalRPN(vector& tokens) {
stack st;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == “+” || tokens[i] ==“-”|| tokens[i] == “*”|| tokens[i] == “/”) {
long long data1 = st.top();
st.pop();
long long data2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(data1 + data2);
if (tokens[i] == "-") st.push(data2-data1);
if (tokens[i] == "*") st.push(data2 * data1);
if (tokens[i] == "/") st.push(data2 / data1);
}
else {
st.push(stoll(tokens[i]));
}
}
int res=st.top();
st.pop();
return res;
}
};