1. 程式人生 > >python--面試題之棧思想判斷字串是否有效

python--面試題之棧思想判斷字串是否有效

給定一個只包含'  [  ]  (  )  {  }  '元素的字串是否有效,滿足以下條件:

  1. 左括號必須用相同的右括號閉合
  2. 左括號必須以正確的順序閉合
  3. 示例::
    1. ‘()’輸出True
    2. ’(){}[]‘輸出True
    3. ’(]‘輸出False
    4. ’([)]‘輸出False
def Judge():
    string=input('請輸入字串')
    left=['{','[','(']
    stack=[]
    for i in string:
        if i in left:
            stack.append(i)
        else:
            if len(list)==0 or not (1<=ord(i)- ord(stack.pop()) <=2):#利用ascll碼差值判斷括號是否為一對
                return False
    return not stack
while True:
    result=Judge()
    print(result)