Leetcode——20. Valid Parentheses
来源:互联网 发布:linux shell usleep 编辑:程序博客网 时间:2024/06/07 15:18
1. 概述
1.1 题目
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 解题思路
这道题是需要判断是否匹配,也就是在一对括号中的括号也是配对的,若为空也算是配对成功。因而从字符串的左边看的话,可以看做是一个堆栈,遇到一个左括号,就进栈;再遇到一个右括号就判断与栈顶的括号是不是配对的,若是配对就弹出去。直到走完整个字符串。最后返回栈是否为空。
2. 编码
class Solution {public: bool isValid(string s) { int len(s.length()); //求出字符串的长度 if(0 == len) return true; if(len % 2 == 1) return false; //长度是奇数的情况 if(2 == len) //两个字符的情况 { char kk = s.at(1) - s.at(0); if(kk==1 || kk==2) return true; else return false; } stack<char> m_stack; for(int i=0; i<len; ++i) { if(m_stack.size() == 0) m_stack.push(s.at(i)); else { char kk = m_stack.top(); //取顶部元素 kk = s.at(i) - kk; if(!(kk==1 || kk==2)) m_stack.push(s.at(i)); else m_stack.pop(); } } return m_stack.empty(); }};
阅读全文
0 0
- LeetCode——20. Valid Parentheses
- Leetcode——20. Valid Parentheses
- LeetCode——Valid Parentheses
- 【leetcode】20—valid parentheses
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- Failed to read candidate component class:
- Coins
- RxJava2:observeOn和subscribeOn的使用
- Mybatis逆向工程,生成java、xml等文件
- 基于mysql Jdbctemplate 的上层封装,maven中央库可引用
- Leetcode——20. Valid Parentheses
- C++ primier(四)
- sp_addlinkedserver在存储过程中使用
- tomcat配置调优
- Android Studio 2.2.2的依赖库版本问题解决方案
- Android获取手机和系统版本等信息的代码
- 构建Spark分布式集群第一步:搭建Hadoop伪分布式环境
- 数字摘要和Hash函数(哈希函数)
- acpi_device_id 中cls的作用