lintcode: 有效的括号序列
2015-10-17 20:14
316 查看
题目:
样例
括号必须依照
挑战
O(n)的时间,n为括号的个数
解题:
数据结构上面讲过的,碰到"[","(","{"入栈,碰到"]"检测栈顶是不是"[",是出栈,不是返回false,对")","}"同理了。开始我用LinkedList实现栈,没有搞好,然后网上看到java有Stack的。import.util.Stack,然后想着写简单点,有错了一路。。。
Java程序:
View Code
总耗时: 409 ms
有效的括号序列
给定一个字符串所表示的括号序列,包含以下字符:'(', ')',
'{',
'}',
'['and
']', 判定是否是有效的括号序列。
样例
括号必须依照
"()"顺序表示,
"()[]{}"是有效的括号,但
"([)]"则是无效的括号。
挑战
O(n)的时间,n为括号的个数
解题:
数据结构上面讲过的,碰到"[","(","{"入栈,碰到"]"检测栈顶是不是"[",是出栈,不是返回false,对")","}"同理了。开始我用LinkedList实现栈,没有搞好,然后网上看到java有Stack的。import.util.Stack,然后想着写简单点,有错了一路。。。
Java程序:
class Solution: # @param {string} s A string # @return {boolean} whether the string is a valid parentheses def isValidParentheses(self, s): # Write your code here stack = [] slen = len(s) for elm in s: if elm=='(' or elm == '[' or elm == '{': stack.append(elm) elif elm==')' or elm == ']' or elm == '}': if len(stack)==0: return False top = stack.pop() if top == '(' and elm== ')': continue elif top == '[' and elm ==']': continue elif top == '{' and elm == '}': continue else: return False if len(stack)==0: return True else: return False
View Code
总耗时: 409 ms
相关文章推荐
- 2015架构冲刺说明事宜
- Java Portlet 规范概述
- 全套字符串匹配算法
- [Android基础]Spanned与SpannableString
- C++实现稀疏矩阵的十字链表表示法
- 全套字符串匹配算法
- Mina、Netty、Twisted一起学习(三):TCP前缀固定大小的消息(Header)
- Android-jni开发
- 滴滴快的_2016_面试题_笔试题_产品经理_题来了
- 转义符
- 《TCP/IP详解 卷一》读书笔记-----动态路由协议
- 何谓集群
- Android 传感器 (详解二)—— 常用传感器
- 安装Docker
- Spring 之注解事务 @Transactional
- Hadoop集群虚拟机网卡的介绍和配置
- UDP TCP区别
- english 释词
- PDF签名应用研究小结
- 代理模式