当前位置:网站首页>Leetcode 20. 有效的括号
Leetcode 20. 有效的括号
2022-07-17 15:36:00 【LuZhouShiLi】
Leetcode 20. 有效的括号
题目

思路
首先遍历完所有的左括号,将每一个左括号对应的右括号全部入栈,然后比较当前s[i]和栈顶的右括号是否相同即可。
代码
class Solution {
public:
bool isValid(string s) {
stack<int> st;
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() == true || st.top() != s[i])
{
// 走到这里 说明栈中没有字符了 或者s[i]是右括号 那么直接返回错误
return false;
}
else
{
st.pop();// st.top() 与 s[i]相等 栈弹出元素
}
}
// 看一下栈是不是空 不为空 说明还有左括号没有被匹配
return st.empty();
}
};
边栏推荐
猜你喜欢

解决:Function rgb is missing argument $green. 的问题

Two misunderstandings of digital transformation

Introduction and Simulation Implementation of string class

Transport layer -------- TCP (I)

Mysql学习笔记-分页-表的创建-数据类型

TCP congestion control details | 7 Surpass TCP
![[embedded unit test] construction of C language unit test framework](/img/d4/ba7e5ffa1a782c2478d1f6682f2637.png)
[embedded unit test] construction of C language unit test framework

HCIP(6)

Leetcode 1252. Number of odd value cells

Total number of blocking and waiting in jconsole thread panel (RPM)
随机推荐
Leetcode 1310. Subarray XOR query
Property analysis of rotate matrix (forwarding)
LeetCode_ 216_ Combined sum III
2022.07.13 summer training personal qualifying (VIII)
03-1、内联函数、auto关键字、typeid、nullptr
LeetCode_77_组合
Flink
Ten minutes from pytorch to mxnet
02-2、缺省参数、函数重载、引用、隐式类型转换、关于报错
TiDB 内存控制文档
C# .NET 云南农信国密签名(SM2)简要解析
STL string input / output overload
Two misunderstandings of digital transformation
Research on Wenhua commodity index
Learning note 3 -- basic idea of machine learning in planning control
STM32F407 NVIC
[wechat applet] use a thousand hand float - rollback
Genesis与BlueRun Ventures展开深度交流
The basic establishment of the sequence table and the related operations of adding, deleting, modifying and querying (the sequence table described in C language)
[unity technology accumulation] realize the mouse line drawing function &linerenderer