【Python】最長括號匹配問題:給定字串,僅包含左括號‘(’和右括號‘)’,它可能不是括號匹配的,設計演算法,找出最長匹配的括號子串
阿新 • • 發佈:2019-02-18
最長括號匹配 示例:
給定字串,僅包含左括號‘(’和右括號‘)’,它可能不是括號匹配的,設計演算法,找出最長匹配的括號子串。
演算法分析
只有在右括號和左括號發生匹配時,才有可能更新最終解。
計算s[0…i]中左括號數目與右括號數目的差x,若x為0時,考察最終解是否可以更新,
這個差x是入棧的數目,程式碼中用“深度”deep表達。
由於可能出現左右括號不相等——尤其是左括號數目大於右括號數目,所以,再從右向左掃描一次。
用deep值替換stack棧,空間複雜度由O(N)降到O(1)。
Python程式碼如下:
def match_longest_parentheses (s):
size = len(s)
li = [] # 記錄最長結果的字串索引,例如:對於"()(()"則返回[[0, 1], [3, 4]]
deep = 0 # 遇到多少左括號
start = 0 # 最深的(deep=0 時)左括號的位置
for i in range(size):
if s[i] == '(':
deep += 1
else: # s[i] == ')'
deep -= 1
if deep == 0:
if len(li) == 0 or li[0][1] - li[0][0] < i - start:
li = [[start, i]]
elif li[0][1] - li[0][0] == i - start:
li.append([start, i])
elif deep < 0: # 說明右括號數目大於左括號數目
deep = 0
start = i + 1
deep = 0 # 遇到多少右括號
start = size - 1 # 最深的(deep=0 時)右括號的位置
for i in range(size - 1, -1, -1):
if s[i] == ')':
deep += 1
else: # s[i] == '('
deep -= 1
if deep == 0:
if len(li) == 0 or li[0][1] - li[0][0] < start - i:
li = [[i, start]]
elif li[0][1] - li[0][0] == start - i and not li.__contains__([i, start]):
li.append([i, start])
elif deep < 0: # 說明左括號數目大於右括號數目
deep = 0
start = i - 1
return li
if __name__ == '__main__':
s = '()(()))(((((()))'
print('字串:%s' % s)
li = match_longest_parentheses(s)
print('最長括號索引:%s' % li)
ss = [s[i[0]:i[1] + 1] for i in li]
print('最長括號:%s' % ','.join(ss))
輸出結果:
字串:()(()))(((((()))
最長括號索引:[[0, 5], [10, 15]]
最長括號子串:()(()),((()))