[LeetCode]Valid Parentheses
来源:互联网 发布:js中join的用法 编辑:程序博客网 时间:2024/06/05 20:13
题目要求如下:
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.
可以完全匹配的,也是valid的一种。解题思路是这样的:我们对字符串S中的每一个字符C,如果C不是右括号,就压入栈stack中。
如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回not valid,非空就取出栈顶的字符pre来对比,如果是匹配
的,就弹出栈顶的字符,继续取S中的下一个字符;如果不匹配,说明不是valid的,直接返回。当我们遍历了一次字符串S后,注意
这里还有一种情况,就是stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的,因为只要valid,一
定全都可以得到匹配使左括号弹出。
以下是我的代码,欢迎各位大牛指导交流~
AC,Runtime: 4 ms
//LeetCode_Valid Parentheses//Written by Zhou//2013.12.28class Solution {public: bool isValid(string s) { stack<char> charStack; size_t i = 0; while(i != s.length()) { char c = s[i]; if (c != ')' && c != '}' && c != ']') { charStack.push(c); } else { if (charStack.size() == 0) return false; char pre = charStack.top(); switch(c) { case ')': if (pre == '(') charStack.pop(); else return false; break; case '}': if (pre == '{') charStack.pop(); else return false; break; case ']': if (pre == '[') charStack.pop(); else return false; break; } } ++i; } if (charStack.size() == 0) return true; else return false; }};
1 0
- LeetCode: Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode: Valid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode : Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Leetcode: Valid Parentheses
- leetcode 52: valid parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [LeetCode]Valid Parentheses
- LeetCode-Valid Parentheses
- 由先序遍历和中序遍历构造二叉树的二叉链表代码
- Windows XP + Apache 2.2.4 + PHP 5.2.3 + MySQL 5.0.27 + Zend Optimizer 3.3.0 Windows XP + Apache + PH
- cppTest-3.0:指针相关-4(字符串函数)
- asp.net mvc 3.0详细笔记__05__项目文件结构详解_Views
- cppTest-3.0:指针相关-x(指针运算)
- [LeetCode]Valid Parentheses
- VC下线程安全退出的方法----百度文章
- Linux驱动开发经典书籍
- 现控-控制系统的状态空间描述
- asp.net mvc 3.0详细笔记__06__项目文件结构详解_Content和Scripts
- Memcached笔记——(二)应对高并发攻击
- android中图片的三级cache策略(内存、文件、网络) 一
- 李强东经典演讲回忆录
- cppTest-3.5:模板函数