📜  数据结构|堆叠问题5

📅  最后修改于: 2021-06-28 17:52:43             🧑  作者: 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
(A) ((())
(B) ())(()
(C) (()()))
(D) (()))()答案: (A)
说明:在while循环结束时,我们必须检查堆栈是否为空。对于输入((()),循环后堆栈不会保持为空。有关详细信息,请参见https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/。