LeetCode小白菜笔记[6]:Valid Parentheses
2017-12-15 19:23
447 查看
LeetCode小白菜笔记[6]:Valid Parentheses
20. Valid Parentheses [Easy]
题目: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.
题目是判别一个表达式是不是有效的,实际上就是看左右括号是不是符合嵌套规范并且一一对应。这道题目比较简单,记忆中应该是数据结构与算法课上用来解释栈的应用的一个例子。每检测到一个左括号,就将其压栈,每遇到一个右括号,先判断栈是否为空,如果空直接 False (说明右括号多了),否则再看如果与栈顶的可以对应,那么就pop出栈顶元素;如果不对应直接 return False。这样检查完所有的括号后,如果栈空了,说明是valid,否则返回 False。
代码如下:
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ paren = {'(': 1, '{' : 2, '[' : 3, ')': -1, '}' : -2, ']' : -3} stack = [] for i in range(len(s)): if paren.has_key(s[i]): if paren[s[i]] > 0 : stack.append(paren[s[i]]) else: if len(stack) == 0: return False elif paren[s[i]] + stack[-1] == 0: stack.pop() else: return False if len(stack) == 0: return True else: return False
( 愚蠢的我又又又又把 str 这个关键字忘了直接当变量名了。。。)修改过后结果如下:
又又又又是勉强通过。。。看了下discuss上的code,如下:
class Solution: # @return a boolean def isValid(self, s): stack = [] dict = {"]":"[", "}":"{", ")":"("} for char in s: if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else: return False return stack == []
runtime快了一些,但是也只是百分之39点多。不过code写法上明显比较好。
总结 :
str是个Python关键字,不要再用作变量名了 - . - b
list元素遍历如果用不到下标的话可以直接 for value in list ,然后 value +=1 这样,而不必 for i in range(len(list)),再 list[i] += 1。
示例代码中的dict直接将匹配的字符作为键值对,更加方便。
直接pop出来比较即可,如果不等于直接 False 不影响结果,如果等于则需要pop,这样就省去一次取值的时间。
像返回boolean这种可以直接 return 判断表达式,不要用 if 语句,显得好笨TAT。
THE END
2017/12/25 Fri 19:20
相关文章推荐
- leetcode笔记--Valid Parentheses
- LeetCode笔记:20. Valid Parentheses
- leetcode笔记:Valid Parentheses
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
- 小白笔记--------------------------leetcode(20. Valid Parentheses )
- leetcode笔记:32.Longest Valid Parentheses
- 【leetcode刷题笔记】Longest Valid Parentheses
- leetcode 32 : Longest Valid Parentheses
- [LeetCode] Valid Parentheses
- leetcode 20 -- Valid Parentheses
- LeetCode_Stack_Valid Parentheses
- leetcode --20. Valid Parentheses
- leetcode 32. Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- Leetcode - 20. Valid Parentheses
- [Leetcode]32. Longest Valid Parentheses @python
- leetcode-Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode (5). Valid Parentheses