2012-11-06 52 views
2

比如有一個字符串s:如何在python字符串中找到相反的字符?

s = "((abc)((123))())blabla" 

我們知道S的開頭「(」我們要找到它的對面,「)」「布拉布拉」之前,如何做到這一點在python中?

是否可以在不使用狀態機的情況下以簡單直觀的方式執行此操作? 還是有任何圖書館可以做到這一點?

+2

http://stackoverflow.com/questions/524548/regular-expression-to- detect-semi-colon-terminated-c-for-while-loops/524624#524624這可能有助於 – Amit

+0

nope,我擔心你無法逃避這類問題的正則表達式 – EnricoGiampieri

+0

@AmitMizrahi非常感謝你,這是一個很好的辦法。所以這個問題應該改變,是否有任何lib做這種事情.. – zchenah

回答

1

您可以嘗試正則表達式,pyparsing,但線性時間複雜度幼稚的選項下面簡單的方式

>>> s = "((abc)((123))())blabla" 
>>> count = 0 
>>> for i,e in enumerate(s): 
    if e == '(': 
     count += 1 
    elif e == ')': 
     count -= 1 
    if not count: 
     break 


>>> s[:i + 1] 
'((abc)((123))())' 
>>> 
+0

謝謝你,這是像我想的那麼簡單。 – zchenah

1

的代碼就可以實現,通過:

from collections import defaultdict 

opens = defaultdict(int) 

open_close_pair = [] 

s = '((abc)((123))())blabla' 
openc, closec = '(', ')' 

for c in range(0, len(s)): 
    if s[c] == openc: 
     # +1 in every entry 
     for key, val in opens.items(): 
      opens[key] += 1 
     opens[c] += 1 

    elif s[c] == closec: 
     # -1 in every entery 
     for key, val in opens.items(): 
      opens[key] -= 1 
    else: 
     pass 

    for key, val in opens.items(): 
     if val == 0: 
      # open the entry to the open close pairs 
      open_close_pair.append((key, c)) 
      # the bracket is close so can be removed from the counter 
      del opens[key] 

for x in open_close_pair: 
    print " %s %s " % (s[x[0]], s[x[1]]) 
print open_close_pair 
print opens 

輸出是:

() 
() 
() 
() 
() 
[(1, 5), (7, 11), (6, 12), (13, 14), (0, 15)] 
defaultdict(<type 'int'>, {}) 

的算法是:

  • 保持一個打開包含的位置字典打開括號。
  • 當你找到一個開放的支架,你以前的所有條目添加+1,比當你發現一個右括號加上當前位置
  • 一個新條目,您減少-1以前所有的enteries
  • 只需運行打開,如果有任何條目爲0意味着我們有一對。
+0

謝謝你我的傢伙我的答案,但我認爲它不夠簡單.. – zchenah