题目链接:20. 有效的括号
出现右括号时查看栈内top元素是否与之匹配,不匹配返回false,匹配则top出栈判断下一个符号是否对应。
压入左括号方法:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
stk.push(s[i]);
}
else if(s[i] == ')') {
if(!stk.empty() && stk.top() == '(') {
stk.pop();
}
else return false;
}
else if(s[i] == ']') {
if(!stk.empty() && stk.top() == '[') {
stk.pop();
}
else return false;
}
else if(s[i] == '}') {
if(!stk.empty() && stk.top() == '{') {
stk.pop();
}
else return false;
}
}
if(stk.empty()) return true;
else return false;
}
};
压入右括号方法:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '(') stk.push(')');
else if(s[i] == '[') stk.push(']');
else if(s[i] == '{') stk.push('}');
else if(stk.empty() || s[i] != stk.top()) return false;
else stk.pop();
}
if(stk.empty()) return true;
else return false;
}
};
题目链接:1047. 删除字符串中的所有相邻重复项
栈:字符入栈之前判断指针指向的字符是否与栈top元素相同,相同则top出栈,否则指针指向字符入栈。
class Solution {
public:
string removeDuplicates(string s) {
string result;
for(int i = 0; i < s.length(); i++) {
if(result.size() == 0) {
result.push_back(s[i]);
}
else if(*(result.end() - 1) == s[i]){
result.pop_back();
}
else {
result.push_back(s[i]);
}
}
return result;
}
};
题目链接:150. 逆波兰表达式求值
遇到运算符就从栈内取两个数进行运算并将结果重新入栈。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for(string s : tokens) {
if(s == "+") {
int i = stk.top();
stk.pop();
i = stk.top() + i;
stk.pop();
stk.push(i);
}
else if(s == "-") {
int i = stk.top();
stk.pop();
i = stk.top() - i;
stk.pop();
stk.push(i);
}
else if(s == "*") {
int i = stk.top();
stk.pop();
i = stk.top() * i;
stk.pop();
stk.push(i);
}
else if(s == "/") {
int i = stk.top();
stk.pop();
i = stk.top() / i;
stk.pop();
stk.push(i);
}
else {
stk.push(str2int(s));
}
}
return stk.top();
}
int str2int(string& s){
int result = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] != '-') {
result *= 10;
result += s[i] - '0';
}
}
if(s[0] == '-') return - result;
else return result;
}
};