20. Valid Parentheses
来源:互联网 发布:android源码下载 编辑:程序博客网 时间:2024/06/14 06:32
DescriptionHintsSubmissionsDiscussSolution
DiscussPick One
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.
Seen this question in a real interview before?
Yes
分析:
有效括号
给定一个仅包含字符() {} [] 的字符串,判断给定的字符串是否正确的标准是 三组括号之间的正确配对
这里典型的使用栈来解题。通过栈的后进先出的规则,如果栈空,则证明是正确的
如果是括号的前半部分,那么我们将压栈,如果是后半部分,就和栈顶元素做比较,看能否进行匹配,如果不能匹配,则返回错误,如果可以,继续进行。最后,如果栈为空,则为有效括号字符串
class Solution {public: bool isValid(string s) { std::stack<char> st; //这里只是说明stack声明的头,std 其实可以直接 stack<char> st;unorderd_map<char,char> maps={{'{','}'},{'(',')'},{'[',']'}};for(int i=0;i<s.size();i++){if(s[i]=='{'||s[i]=='('||s[i]=='[')st.push(s[i]);else{if(st.empty())return false;t=st.top(); //这个是取顶的值st.pop(); //出栈if(maps[t]!=s[i]) //如果出栈的括号的另一半不能正确匹配当前的s[i]return false;}}return st.empty(); }};
阅读全文
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 20.Valid Parentheses
- 20.Valid Parentheses
- 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 20. Valid Parentheses
- 20. Valid Parentheses
- 对dataframe中数据处理的办法:
- Expectation Maximization(EM)算法
- vue tab切换
- 静态导入Static import
- *sdnu1483.Problem_A
- 20. Valid Parentheses
- 创建抽象类 Transport
- Ubuntu 16.04编译安装最新的OpenCV3.2
- Android 网络连接的判断
- Servlet详解
- get和post的区别
- Python生成器(Generator)详解
- 凑数字游戏
- Hibernate常用配置