Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
1 2 |
<strong>输入:</strong> "()" <strong>输出:</strong> true |
示例 2:
1 2 |
<strong>输入:</strong> "()[]{}" <strong>输出:</strong> true |
示例 3:
1 2 |
<strong>输入:</strong> "(]" <strong>输出:</strong> false |
示例 4:
1 2 |
<strong>输入:</strong> "([)]" <strong>输出:</strong> false |
示例 5:
1 2 |
<strong>输入:</strong> "{[]}" <strong>输出:</strong> true |
解答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ dict = { '(':')', '[':']', '{':'}' } start = '' if len(s)%2 !=0: return False try: for i in s: if i in dict: start = start + i elif dict[start[-1]] == i: start = start[:-1] else: return False if start == '': return True return False except: return False |
自测用例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
try: print('---test1---') str = '()' prefix = Solution().isValid(str) print('true - {}'.format(prefix)) except Exception as e: print(e) try: print('---test2---') str = "()[]{}" prefix = Solution().isValid(str) print('true - {}'.format(prefix)) except Exception as e: print(e) try: print('---test3---') str = "([)]" prefix = Solution().isValid(str) print('false - {}'.format(prefix)) except Exception as e: print(e) try: print('---test4---') str = "(]" prefix = Solution().isValid(str) print('false - {}'.format(prefix)) except Exception as e: print(e) try: print('---test5---') str = "((" prefix = Solution().isValid(str) print('false - {}'.format(prefix)) except Exception as e: print(e) try: print('---test6---') str = "]" prefix = Solution().isValid(str) print('false - {}'.format(prefix)) except Exception as e: print(e) try: print('---test7---') str = "[" prefix = Solution().isValid(str) print('false - {}'.format(prefix)) except Exception as e: print(e) |
结果
提交时间 | 状态 | 执行用时 | 语言 |
---|---|---|---|
几秒前 | 通过 | 44 ms | python3 |