括號匹配程式設計題--python
阿新 • • 發佈:2019-02-09
#!/usr/bin/python
#-*- coding: utf8 -*-
def isMatched(inStr):
"""
Judge whether the input match rules
@author: ken
>>>isMatched('{}{}(())')
>>>True
>>>isMatched('{)}(')
>>>False
>>>isMatched('([]')
>>>False
"""
b_match = True
matchs = {"{": "}", "(": ")", "[": "]"}
while (b_match and len(inStr) != 0):
w = inStr[0]
if (not matchs.has_key(w)) or (inStr.find(matchs[w]) == -1):
b_match = False
else:
inStr = inStr.replace(w, '', 1)
inStr = inStr.replace(matchs[w], '', 1)
return b_match
if __name__ == '__main__':
inStr = "([)]"
print isMatched(inStr)
#-*- coding: utf8 -*-
def isMatched(inStr):
"""
Judge whether the input match rules
@author: ken
>>>isMatched('{}{}(())')
>>>True
>>>isMatched('{)}(')
>>>False
>>>isMatched('([]')
>>>False
"""
b_match = True
matchs = {"{": "}", "(": ")", "[": "]"}
while (b_match and len(inStr) != 0):
w = inStr[0]
if (not matchs.has_key(w)) or (inStr.find(matchs[w]) == -1):
b_match = False
else:
inStr = inStr.replace(w, '', 1)
inStr = inStr.replace(matchs[w], '', 1)
return b_match
if __name__ == '__main__':
inStr = "([)]"
print isMatched(inStr)