2023年4月28日 星期五

4/28 每日一題 (括號是否是對映)

 Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. 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_lis
                s_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
               

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁