題目連接:https://leetcode-cn.com/problems/valid-parentheses/java
給定一個只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判斷字符串是否有效。python
有效字符串需知足:app
注意空字符串可被認爲是有效字符串。spa
示例 1:code
輸入: "()" 輸出: true
示例 2:leetcode
輸入: "()[]{}" 輸出: true
示例 3:字符串
輸入: "(]" 輸出: false
示例 4:get
輸入: "([)]" 輸出: false
示例 5:io
輸入: "{[]}" 輸出: true
匹配問題,咱們通常使用棧class
遍歷字符串,咱們把左括號壓入棧中,當遇到右括號,和棧頂元素比較!
時間複雜度:\(O(n)\)
空間複雜度:\(O(n)\)
關注個人知乎專欄,瞭解更多的解題技巧!
python
class Solution: def isValid(self, s: str) -> bool: stack = [] lookup = { "(":")", "[":"]", "{":"}" } for alp in s: if alp in lookup: stack.append(alp) continue if stack and lookup[stack[-1]] == alp: stack.pop() else: return False return True if not stack else False
java
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char alp : s.toCharArray()) { if (alp == '(') stack.push(')'); else if (alp == '[') stack.push(']'); else if (alp == '{') stack.push('}'); else if (stack.isEmpty() || stack.pop() != alp) return false; } return stack.isEmpty(); } }