20. Valid Parentheses leetcode Python 2016 new Season
2016-01-07 10:41
741 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
Show Company Tags
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
Discuss
need O(n) time to go through the whole array and worst case O(n) space to store the array.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for index in range(len(s)):
current_string = s[index]
if current_string == '(' or current_string == '[' or current_string == '{':
stack.append(current_string)
if current_string == ')':
if not stack or stack.pop() != '(':
return False
if current_string == ']':
if not stack or stack.pop() != '[':
return False
if current_string == '}':
if not stack or stack.pop() != '{':
return False
if stack:
return False
return True
'(',
')',
'{',
'}',
'['and
']',
determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are
all valid but
"(]"and
"([)]"are
not.
Show Company Tags
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
Discuss
need O(n) time to go through the whole array and worst case O(n) space to store the array.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for index in range(len(s)):
current_string = s[index]
if current_string == '(' or current_string == '[' or current_string == '{':
stack.append(current_string)
if current_string == ')':
if not stack or stack.pop() != '(':
return False
if current_string == ']':
if not stack or stack.pop() != '[':
return False
if current_string == '}':
if not stack or stack.pop() != '{':
return False
if stack:
return False
return True
相关文章推荐
- Python列表
- 关于python中的虚拟环境 virtualenv
- python编写脚本应用实例
- 笨方法学Python(41-45)
- Python时间,日期,时间戳之间转换
- 用Python实现古诗词填字游戏(二)
- Python风格规范
- 4.3. The range() Function(range 函数)
- python高手之路python处理excel文件(方法汇总)
- python zip(), map()
- Python解析最简单的验证码
- 4.2. for Statements(for 语句)
- 4.1. if Statements(if 语句)
- Python数据科学安装Numby,pandas,scipy,matpotlib等(IPython安装pandas)
- Python数据科学安装Numby,pandas,scipy,matpotlib等(IPython安装pandas)
- 【LEETCODE】11-Container With Most Water [Python]
- python之路--线程和进程
- Python的垃圾回收机制
- Python web开源框架整理
- 持续集成学好jenkins之内置命令