背景:查找括号是否平衡的问题实际上是一个决策问题,描述它的语言1是context-free language。
上下文无关语法可以使用带有堆栈的自动机进行解析2
所以,对于这个问题,可以实现以下迭代解:
iterative(str):
stack <- empty stack
for each char in str:
if char is open paranthesis: //push the paranhtesis to stack
stack.push(char)
else if char is close parantesis: //if close paranthesis - check if it is closing an open parenthesis
if stack.head() == matchingParanthesis(char):
stack.pop()
else: //if the closing parenthesis do not close anything previously opened, return false
return false
//end of loop - check if all opened parenthesis were closed:
return stack.isEmpty()
这个想法是表示打开的范围的括号位于堆栈的头部,并且每个右括号 - 您可以通过查看堆栈的头部来验证它是否正在关闭适当的打开的括号。
注意:很容易看出,对于单个类型的括号,我们可以使用整数来模拟堆栈(因为我们实际上只需要计算数字,而不关心括号的类型)。
另外,由于循环+堆栈算法实际上与递归非常相似,我们可以推导出以下递归算法:
checkValidty(str,currentParenthesis,currentIndex):
//currentIndex is a common variable, changed by reference to affect all levels of recursion!
while (currentIndex < str.size()):
char <- str[currentIndex]
currentIndex <- currentIndex + 1
if char is open paranthesis:
//if the recursive call is unseccesfull - end the check, the answer is no
if !checkValidity(str,char,currentIndex):
return false
else if char is close parantesis:
if currentParenthesis == matchingParanthesis(char):
return true
else: //if the closing parenthesis do not close anything previously opened, return false
return false
//end of loop - check if all opened parenthesis were closed:
return currentParenthesis == nil
使用checkValidty(str,nil,0) 调用 - 其中str 是经过验证的字符串。
很容易看出,迭代和递归算法其实是一样的,第二次我们使用调用栈和变量lastParenthesis作为栈头。
(1) 语言是问题所接受的所有词。例如(w) 是语言,而)w( 不是。
(2) 确切地说:有些语法需要一个非确定性自动机和一个堆栈,但这是一个更理论的东西,而不是这里的问题。