【问题标题】:Recursive algorithm to check whether String has Balanced Parenthesis [duplicate]递归算法检查字符串是否具有平衡括号[重复]
【发布时间】:2012-09-14 09:05:07
【问题描述】:

可能重复:
Basic Recursion, Check Balanced Parenthesis

我最近在算法设计手册中遇到了这个问题,尽管基于堆栈的算法非常简单,但我想为这个问题编写一个递归算法,但是作为递归的菜鸟,我无法想出太多,那么有人可以帮我解决这个问题吗?

PS 我只看到了关于这个问题的其他帖子,但它们效率不高,而且那些不是很解释。

【问题讨论】:

  • 如果你只有一种类型的括号,你可以有一个更简单的递归算法,你只需要记住开括号的级别,如果它低于0,括号是不平衡的,否则,如果最后是0,括号是平衡的。

标签: algorithm data-structures recursion solution


【解决方案1】:

背景:查找括号是否平衡的问题实际上是一个决策问题,描述它的语言1context-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) 确切地说:有些语法需要一个非确定性自动机和一个堆栈,但这是一个更理论的东西,而不是这里的问题。

【讨论】:

  • 它有一个更简单的版本:stackoverflow.com/a/2718114/496223 在递归调用中执行一段时间似乎有点奇怪,因为您只需要利用通常由递归创建的堆栈
猜你喜欢
  • 2013-12-28
  • 1970-01-01
  • 2013-02-02
  • 2018-06-23
  • 2013-11-18
  • 2011-11-04
  • 2015-03-19
  • 2011-02-12
  • 2013-02-03
相关资源
最近更新 更多