4/28 每日一題 (括號是否是對映)
Given a string s 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.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false參考解答:class Solution:def isValid(self, s: str) -> bool:s_lis=[]for i in s:if i == "(" or i =="[" or i == "{":#左邊符號加入到s_liss_lis.append(i)else:if not s_lis:#如果是空集合就表示不成對return False#當i讀取到第一個右邊符號時,我的左邊符號列表必定是他成對的另一邊if i == ")" and s_lis[-1] =="(":s_lis.pop()elif i == "]" and s_lis[-1] =="[":s_lis.pop()elif i == "}" and s_lis[-1] =="{":s_lis.pop()else:#表示沒有對映的return False#如果回圈執行完 s_lis還有剩餘表示沒有完全配對成功,沒有剩餘表示正確return not s_lis
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁