stack栈是一种先进后出的数据结构
初始化:
stack<char> stk;//初始化一个字符类型的栈,名字是stk
empty函数用来检查栈是否为空,如果为空返回真,不为空返回假
top返回栈顶的元素
pop用来弹出栈顶的元素
push用来将元素放到栈顶
if(stk.empty())
{
cout << "stk is empty" << endl;
}
else
{
cout << "the top is " << stk.top() << endl;
stk.pop();
}
stk.pop('y');//插入y这个字符
给一道例题
力扣:有效的括号
https://leetcode.cn/problems/valid-parentheses/description/?envType=study-plan-v2&envId=top-interview-150
思路:
每次看是不是右括号,如果是就检查栈顶是不是对应左括号,如果不是就放到栈顶
代码:
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if(n % 2 == 1)
{
return false;
}
unordered_map<char,char> pair =
{
{')','('},
{']','['},
{'}','{'}
};
stack<char> stk;
for(auto ch : s)
{
if(pair.count(ch))
{
if(stk.empty() || stk.top() != pair[ch])
{
return false;
}
stk.pop();
}
else
{
stk.push(ch);
}
}
return stk.empty();
}
};