表达式括号匹配

 

Hint 1

 

  关于有效括号表达式的一个有趣属性是有效表达式的子表达式也应该是有效表达式。 例如

 

  • { { } [ ] [ [ [ ] ] ] }  有效

 

  • [ [ [ ] ] ]    有效

 

  • { } [ ]     有效

 

  我们能以某种方式利用这种递归结构吗?

  此外,如果仔细查看上述结构,颜色编码的单元格将标记开括号和闭合对。 整个表达式是有效的,但它的子部分本身也有效。

这为问题提供了一种递归结构。 对于例如 考虑上图中两个绿色括号内的表达式。 索引1处的开口括号和索引6处的相应闭合括号。

 

Hint 2

  如果每当我们在表达式中遇到一对匹配的括号时,我们只是从表达式中删除它? 这将继续缩短表达。 例如

 

  • { { ( {  } ) } }

               |_|

  •   { { (       ) } }

               |___|

  • { {           } }

           |_____|

  •  {                }

         |________|

有效

 

Hint 3

  在表示问题的递归结构时,栈可以派上用场。 我们无法从内到外真正地处理这个问题,因为我们对整体结构一无所知。

但是,栈可以帮助我们递归地处理这种情况,即从外部到内部。

 

 

Algorithm

 

  1. 初始化堆栈S。
  2. 一次处理一个表达式的每个括号。
  3. 如果我们遇到一个左括号,我们只需将它入栈即可。 这意味着我们将在稍后处理它,让我们简单地转移到子表达式。
  4. 如果我们遇到右括号,那么我们检查栈顶元素。 如果堆元素是相同类型的左括号,那么我们将它从堆栈中弹出并继续处理。否则,这意味着表达式无效。
  5. 最后,如果堆栈仍不为空,那么这意味着这是一个无效的表达式。

 

 

 

// CPP program to check for balanced parenthesis. 
#include<bits/stdc++.h> 
using namespace std; 
  
// function to check if paranthesis are balanced 
bool areParanthesisBalanced(string expr) 
{ 
    stack<char> s; 
    char x; 
  
    // Traversing the Expression 
    for (int i=0; i<expr.length(); i++) 
    { 
        if (expr[i]=='('||expr[i]=='['||expr[i]=='{') 
        { 
            // Push the element in the stack 
            s.push(expr[i]); 
            continue; 
        } 
  
        // IF current current character is not opening 
        // bracket, then it must be closing. So stack 
        // cannot be empty at this point. 
        if (s.empty()) 
           return false; 
  
        switch (expr[i]) 
        { 
        case ')': 
  
            // Store the top element in a 
            x = s.top(); 
            s.pop(); 
            if (x=='{' || x=='[') 
                return false; 
            break; 
  
        case '}': 
  
            // Store the top element in b 
            x = s.top(); 
            s.pop(); 
            if (x=='(' || x=='[') 
                return false; 
            break; 
  
        case ']': 
  
            // Store the top element in c 
            x = s.top(); 
            s.pop(); 
            if (x =='(' || x == '{') 
                return false; 
            break; 
        } 
    } 
  
    // Check Empty Stack 
    return (s.empty()); 
} 
  
// Driver program to test above function 
int main() 
{ 
    string expr = "{()}[]"; 
  
    if (areParanthesisBalanced(expr)) 
        cout << "Balanced"; 
    else
        cout << "Not Balanced"; 
    return 0; 
} 

 

 

 

posted @ 2019-03-04 09:21  XLimp  阅读(369)  评论(0)    收藏  举报