📜  数据结构 |堆栈 |问题 5

📅  最后修改于: 2021-09-08 12:49:06             🧑  作者: Mango

以下是用于确定括号序列是否平衡的算法的错误伪代码:

declare a character stack 
while ( more input is available)
{
   read a character
   if ( the character is a '(' ) 
      push it on the stack
   else if ( the character is a ')' and the stack is not empty )
      pop a character off the stack
   else
      print "unbalanced" and exit
 }
 print "balanced"

上面的代码认为这些不平衡序列中的哪个是平衡的?

资料来源:http://www.cs.colorado.edu/~main/questions/chap07q.html
(一) ((())
(B) ())(()
(C) (()()))
(D) (()))()答案:(一)
说明:在while循环结束时,我们必须检查堆栈是否为空。对于输入 ((()),循环后堆栈不会保持为空。有关详细信息,请参阅 https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/。