Easy-题目47:20. Valid Parentheses
2016-05-30 20:39
423 查看
题目原文:
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.
题目大意:
给出一个括号字符串,判断括号是否正确匹配。
题目分析:
本题考查堆栈的使用,遇到左边的括号全部入栈,遇到右边的括号则看栈顶的括号是不是对应的左括号,如是则弹出,如不是则返回错误。如果整个括号字符串扫完之后栈恰好为空,则是合法匹配。
源码:(language:python)
成绩:
43ms,beats 55.57%,众数40ms,27.91%
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.
题目大意:
给出一个括号字符串,判断括号是否正确匹配。
题目分析:
本题考查堆栈的使用,遇到左边的括号全部入栈,遇到右边的括号则看栈顶的括号是不是对应的左括号,如是则弹出,如不是则返回错误。如果整个括号字符串扫完之后栈恰好为空,则是合法匹配。
源码:(language:python)
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack=[] for c in s: if c in ['(','[','{']: stack.append(c) else: if(len(stack)==0): return False top=stack[len(stack)-1] if ((c == ')' and top=='(') or (c == ']' and top=='[') or (c == '}' and top == '{')): stack.pop() else: return False return len(stack)==0
成绩:
43ms,beats 55.57%,众数40ms,27.91%
相关文章推荐
- 智能dns-dns日志系统-dns压力测试整理
- new一个对象的过程
- 【HDU】 1431 素数回文
- POJ 1664 放苹果 (递推)
- Core Data浅谈初级入门
- 第二阶段个人工作总结(3)
- 神经网络浅析
- Easy-题目46:205. Isomorphic Strings
- corosync v2 + pacemaker 高可用mariadb服务
- Android基础知识整合篇——Activity知识点
- 怎么快速看懂别人写的module和ipcore
- 视图
- Java性能提高小常识
- Easy-题目45:58. Length of Last Word
- 什么是一阶逻辑(First-order Logic)
- GCC编译和GDB调试
- memched1.0源码阅读(3)——运行流程
- TS流打包总结
- 二叉搜索树的查找、插入、删除操作
- tushare金融数据