Python learning algorithm day10: Stack Application (parenthesis matching)

Stack

Stack of applications - matching brackets

括号匹配问题: 给一个字符串, 其中包括小括号, 中括号, 大括号, 求该字符串中的括号是否匹配
例如:
	- (){}[] 匹配
	- ([{}]) 匹配
	- ([)]   不匹配
	- ())    不匹配

Code:

def brace_match(s):
	stack = []
	dic = {'(':')', '{':'}', '[':']'}
	for ch in s:
		if ch in {'(', '{', '['}:
			stack.append(ch)
		elif len(stack) == 0:
			print('多了右括号%s' % ch)
			return False
		elif dic[stack[-1]] == ch:
			stack.pop()	
		else:
			print('括号%s处不匹配' % ch)
			return False
	if len(stack) == 0:
		return True
	else:
		print('剩余左括号未匹配')
		return False
Published 126 original articles · won praise 35 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43442524/article/details/104179401
Recommended