0基础力扣 DAY11
20. 有效的括号
思路:设置一个栈,将扩号字符串插入栈中,若当前字符为左括号,则直接入栈,若为右括号,则查找栈顶元素,判断是否为匹配的左括号,若栈为空,则返回false,若不匹配则返回false,匹配则将栈顶元素弹出,指针后移,继续判断后续括号是否符合
代码如下:
class Solution {
public:
bool isValid(string s) {
std::stack<char, std::vector<char>> S;
for(int i=0; i<s.size(); i++){
if(s[i]=='(' || s[i]=='{' || s[i] == '['){ //遍历到左括号,直接入栈
S.push(s[i]);
continue;
}
if(s[i]==')') //遍历到右括号,和栈顶元素进行匹配
if(!S.empty() && S.top() == '(')
S.pop();
else
return false;
if(s[i]=='}')
if(!S.empty() && S.top() == '{')
S.pop();
else
return false;
if(s[i]==']')
if(!S.empty() && S.top() == '[')
S.pop();
else
return false;
}
if(S.empty()) // 检查栈是否为空
return true;
else
return false;
}
};
1047. 删除字符串中所有相邻重复项
题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
思路:设置一个初始为空的栈,遍历字符数组,若栈为空,将当前元素入栈;若栈非空,比较当前元素与栈顶元素,相同则弹栈,指针后移,不相同则将当前元素入栈,直到遍历完整个字符数组,此时栈中存放的即为最终结果,倒序输出即可。
代码如下:
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. 逆波兰表达式求值
题目链接:150. 逆波兰表达式求值 - 力扣(LeetCode)
思路:设置一个初始为空的栈,遍历数组,当前元素为数字时直接入栈;元素为符号时,依次弹出栈顶的两个元素,进行运算,结果入栈。完成遍历后,栈中存放的数字即为最终结果。
代码如下:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
// 力扣修改了后台测试数据,需要用longlong
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();
st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
return result;
}
};