Python 題目

PROBLEM

Python Day 2

#python #程式碼

題目:

st 的內容包括數字、加減乘除、小括號。如同一般小括號的用法, 在一組小括號中可以包括另一組小括號, 請找出 st 中的小括號最多 有幾層? 例如: ((1) + ((2) + 3) + 4)

1 有 2 層, 如((1) + ((2) + 3) + 4)

2 有 3 層, 如((1) + ((2) + 3) + 4)

3 有 2 層, 如((1) + ((2) + 3) + 4)

4 有 1 層, 如((1) + ((2) + 3) + 4)

def counts():
    response = [i for i in input()]
    temp = 0
    ans = 0
    for i in response:
        if i == "(":
            temp += 1
            ans = max(ans,temp)
        elif i == ")":
            temp -= 1
    return ans

print(counts())

利用左右括號去判斷他有多少層,當遇到左括號就+1,而遇到右括號就-1