【Leetcode】【Easy】Valid Parentheses
2024-08-25 18:21:29
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
解题思路:
栈使用的典型题目;
解题步骤:
1、新建一个栈;
2、遍历字符串:
(1)符号的左半边,则入栈;
(2)符号的右半边,则pop出栈顶元素,如果栈为空,则返回false;
判断此右半边和栈顶元素是否匹配;匹配继续;不匹配则返回false;
3、循环结束后栈为空,则true,不为空则false;
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int len = s.length(); for(int i = ; i < len; ++i) {
if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
if (st.empty())
return false;
char c = st.top();
if ((c == '(' && s[i] != ')') || \
(c == '[' && s[i] != ']') || \
(c == '{' && s[i] != '}'))
return false;
st.pop(); } else {
st.push(s[i]);
}
} return st.empty();
}
};
附录:
常见符号ASCII码
C++常见容器使用及公式
最新文章
- 版本管理工具SVN
- Chrome浏览器Network面板http请求时间分析
- SO单号中某两项没进FP
- 定制Asp.NET 5 MVC内建身份验证机制 - 基于自建SQL Server用户/角色数据表的表单身份验证
- [Angularjs]ng-switch用法
- ctDNA 相关网站-liquid-biopsy
- HDU4515+计算日期
- 解决TextView与RadioGroup不对齐的问题
- Codeforces Round #252 (Div. 2) 441B. Valera and Fruits
- centos 6.4 x64安装bugfree
- java从文件中读取json
- 【BZOJ 4652】【NOI 2016】循环之美
- btcpool之JobMaker
- Maven pom.xml文件详解
- python 之 列表与字典
- Vue单元测试Karma+Mocha
- 《Mysql 日志结构》
- GO富集分析
- yum节省安装时间
- nginx unit 1.8 支持基于java servlet 的开发模型