diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" index 3bded5a32287cfec435f1237c974e563702c9e98..6516aa1b53ed0c47efd7abe27e8229e37bd23a5b 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" @@ -114,6 +114,28 @@ char leftOf(char c) { ======其他语言代码====== +### Python3 +```python +def isValid(self, s: str) -> bool: + left = [] + leftOf = { + ')':'(', + ']':'[', + '}':'{' + } + for c in s: + if c in '([{': + left.append(c) + elif left and leftOf[c]==left[-1]: # 右括号 + left不为空 + 和最近左括号能匹配 + left.pop() + else: # 右括号 + (left为空 / 和堆顶括号不匹配) + return False + + # left中所有左括号都被匹配则return True 反之False + return not left +``` + + ```java //基本思想:每次遇到左括号时都将相对应的右括号')',']'或'}'推入堆栈 //如果在字符串中出现右括号,则需要检查堆栈是否为空,以及顶部元素是否与该右括号相同。如果不是,则该字符串无效。 @@ -137,3 +159,4 @@ public boolean isValid(String s) { ``` +