leetcode-20. Valid Parentheses
2016-04-27 21:30
441 查看
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.
思路:用stack,左括号进栈,右括号判断栈顶的是否是对应左括号,是的话出栈,否则false,循环最后栈为空则true
The brackets must close in the correct order, “()” and “()[] {}” are all valid but “(]” and “([)]” are not.
思路:用stack,左括号进栈,右括号判断栈顶的是否是对应左括号,是的话出栈,否则false,循环最后栈为空则true
#include<string> using namespace std; class Solution { stack<char> myStack; public: bool isValid(string s) { for(int i=0;i<s.size();i++) { switch(s[i]) { case '(': case '[': case '{': myStack.push(s[i]); break; case ')': if(myStack.empty() || myStack.top() != '(') { return false; } myStack.pop(); break; case ']': if(myStack.empty() || myStack.top() != '[') { return false; } myStack.pop(); break; case '}': if(myStack.empty() || myStack.top() != '{') { return false; } myStack.pop(); break; } } if(myStack.empty()) { return true; } return false; } };
相关文章推荐
- 【Linux】Red Hat Linux 图形界面切换命令界面
- Mybatis最入门---分页查询(拦截器分页原理及实现)
- python中文编码坑
- Power Designer使用方法
- UVA 10245 The Closest Pair Problem【分治】
- JAVA——如何停止线程呢?(interrupt)
- 杭电2006
- 如何避免大量重复URL被百度收录
- UVA 10245 The Closest Pair Problem【分治】
- UVA 10245 The Closest Pair Problem【分治】
- 透过代理获取客户端请求的真实ip
- leetcode 86. Partition List
- php示例代码
- leetcode 046 Permutations
- String和Stingbuffer赋值""区别
- leetcode-19. Remove Nth Node From End of List
- 算法
- double linked list双向链表
- 扩展欧几里得
- Laravel 5 开发API(Dingo Api + JWT)