c++使用棧實現括號匹配

c++使用棧實現括號匹配

給定一個表達式e,包含各種字符,如字母數字運算符標點空格和括號()[]{}等, 判斷其中括號是否匹配,如是,則返回0, 否則根據錯誤類型返回1-3:
錯誤類型包括1、2、3類型:
類型1:
左右括號不匹配,如"(]", “(((]))))”, “((}”,“let {x=a[0)*(b+c); y=b}”
類型2:
發現有左括號不存在與之匹配的右括號,如"(", “(([]”, “()(()”
類型3:
發現右括號不存在與之匹配的左括號,如")", “())”,"(())()"。

代碼:

#include<iostream>
#include<stack>
#include<cstring>
#include<cstdio>
using namespace std;
int matches(string a){
	stack<char> s;
	int l=a.length(),label=0;
    char t;
	for(int i=0;i<l;++i)
    {
        if(a[i]=='('||a[i]=='['||a[i]=='{')
        {
            s.push(a[i]);
        }
        if(a[i]==')'||a[i]==']'||a[i]=='}')
        {
		if(s.empty())return 3;
        else 
		{
		
        if(a[i]==')')
        {
        	t=s.top();
           if(t=='(')s.pop();
           else
           {
                label=1;
           		s.pop();
           		return 1;
	        }
			   
           
        }
        if(a[i]==']')
        {
           t=s.top();
           if(t=='[')s.pop();
           else
           {
           	    label=1;
           	    s.pop();
           		return 1;
			   
           }
        }
        if(a[i]=='}')
        {
           t=s.top();
           if(t=='{')s.pop();
           else
           {
		   
           		label=1;
           		s.pop();
           		return 1;   
           }
        }
		}
		}
    }
       if(!s.empty())return 2;
       if(s.empty()&&label!=1) return 0;
	
}
int main()
{
    string a;
    cin>>a;
    cout<<matches(a)<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章