符号匹配

bool isbalance(const string &str)
{
    string::size_type len = str.size();
    stack<char> Mystack;
    for(string::size_type i = 0; i < len ; ++ i)
    {        
        /*first selection*/
         if(str[i] == '[' || str[i] == '{' || str[i] == '(' || str[i] == '<')
         {
             Mystack.push(str[i]);
         } 
         /*如果是对称的符号,则从栈中弹出*/
         if(str[i] == ']' || str[i] == '}' || str[i] == ')' || str[i] == '>')
         {
             /*如果栈中没有对象,则说明不平衡*/
             if(Mystack.empty())
             {
                 cout << "the string is Unblanced" << endl;
                 return false;
             }
             /*采用switch-case语句判断*/
             switch(str[i])
             { 
             case ']':
                 { 
                     /*判断是否是匹配的*/
                     char tem = Mystack.top();
                     Mystack.pop();
                     if('[' != tem)
                     {
                         cout << "Can not blanced with ]" << endl;
                         return false;
                     }
                     break;
                 }
             case ')':
                 { 
                     /*判断是否是匹配的*/
                     char tem = Mystack.top();
                     Mystack.pop();
                     if('(' != tem)
                     {
                         cout << "Can not blanced with )" << endl;
                         return false;
                     }
                     break;
                 }
             case '}':
                 { 
                     /*判断是否是匹配的*/
                     char tem = Mystack.top();
                     Mystack.pop();
                     if('{' != tem)
                     {
                         cout << "Can not blanced with }" << endl;
                         return false;
                     }
                     break;
                 }
             case '>':
                 { 
                     /*判断是否是匹配的*/
                     char tem = Mystack.top();
                     Mystack.pop();
                     if('<' != tem)
                     {
                         cout << "Can not blanced with >" << endl;
                         return false;
                     }
                     break;
                 }
                 /*一般的非对称字符*/
             default:
                 break;
             }
         }
    }

     /************************************************
      *当所有对象遍历完成以后,需要判断栈中是否存在对象
      *栈中为空说明是平衡的,非空则说明是非空的对象
     ************************************************/

    if(Mystack.empty())
    {
         cout << "string is blanced!!" << endl;
         return true;
    }
    else/*没有正确的匹配,并输出具体不匹配的符号*/
    {
        char tem = Mystack.top();
        Mystack.pop();
        cout << tem << " " << "Unblance string!!" << endl;
        return false;
    }
}
原文地址:https://www.cnblogs.com/shanguanghui/p/2993947.html