leetcode-20-valid-parentheses

题目描述:

给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

Solution by me

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
res = []
for i in range(len(s)):
if s[i] in "([{":
res.append(s[i])
else:
if len(res) == 0:
return False
k = res.pop()
if (s[i] == ")" and k == '(') or \
(s[i] == ']' and k == '[') or \
(s[i] == '}' and k == '{'):
pass
else:
return False
if len(res) == 0:
return True
else:
return False

Solution 2

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''