括号匹配问题
一.初級括號匹配
1.括號匹配原則:
右括號“)”與前面最近的尚未配對的左括號“(”匹配,“(”具有最先掃描到的最后匹配的特點。
后到先處理,因此可以使用棧
有以下這些不匹配的情況:
- (1+2)*(3-4)+5(+6
- (1+2*(3-4)+(5-2)+6
- )2+3(
2.過程分析:
輸入:字符串str存儲的算術表達式
輸出:0表示匹配,1表示多左括號,-1表示多右括號
(1)定義順序棧s
(2)讀取str[i]中的字符:
- ? ?若為‘(’則入棧
- ? ?若為')'且棧非空,則從棧中彈出一個‘(’,說明二者相匹配;
- ? ? 若為')'且棧空,則返回-1
(3)掃描字符串完成后:
- ? ? 若棧空,則返回0,說明括號匹配
- ? ? 若棧非空,則返回1,說明多左括號
3.具體實現:
#include <iostream> //括號匹配問題 using namespace std;class Matcher{ public:Matcher(string str);~Matcher();int match(); private:string str; }; Matcher::Matcher(string str){this->str=str; } Matcher::~Matcher(){} Matcher::match(){char s[100];//順序棧int i,top;top=-1;for(i=0;str[i]!='\0';i++){if(str[i]==')')if(top>-1)//出棧前判斷是否為空top--;else return -1;//棧空,多右括號else if(str[i]=='(')s[++top]=str[i];//入棧}if(top==-1)return 0;//匹配else return 1;//棧中有左括號,多左括號 } int main() {string str;cout<<"請輸入一個算術表達式:"<<endl;cin>>str;Matcher m(str);int k=m.match();if(k==0)cout<<"括號匹配"<<endl;else if(k==1)cout<<"多左括號"<<endl;else if(k==-1)cout<<"多右括號"<<endl;return 0; }二.復雜括號匹配
1.括號匹配原則:有{},[],()三種括號,不允許三種括號的左右括號相互匹配
? ?比如{)、[}、(}、(]都是錯誤的
2.過程分析:
輸入:字符串str存儲的算術表達式
輸出:0表示匹配,1表示多左括號,-1表示多右括號
(1)定義順序棧s
(2)讀取str[i]中的字符:
- ? ?若為‘(’、‘[’、‘{’則入棧
- ? ?若為')'、‘]’、‘}’且棧非空,則從棧中彈出一個左括號,并比較左右括號是否同級匹配;
- ? ?若為')'、‘]’、‘}’且棧空,則返回-1
(3)掃描字符串完成后:
- ? ? 若棧空,則返回0,說明括號匹配
- ? ? 若棧非空,則返回1,說明多左括號
3.具體實現:
#include <iostream> //復雜括號匹配問題 using namespace std;class Matcher{ public:Matcher(string str);~Matcher();int match(); private:string str; }; Matcher::Matcher(string str){this->str=str; } Matcher::~Matcher(){} Matcher::match(){char s[100];//順序棧int i,top;top=-1;for(i=0;str[i]!='\0';i++){switch(str[i]){case ')':{if(s[top]=='('&&top>-1)//判斷是否同級匹配,出棧前是否為空top--;elsereturn 1;//不匹配或者棧空,多右括號}case '}':{if(s[top]=='{'&&top>-1)top--;elsereturn 1;}case ']':{if(s[top]=='['&&top>-1)top--;elsereturn 1;}}if((str[i]=='(')||(str[i]=='[')||(str[i])=='{')s[++top]=str[i];//入棧}if(top==-1)return 0;//匹配elsereturn 1; } int main() {string str;cout<<"請輸入一個算術表達式:"<<endl;cin>>str;Matcher m(str);int k=m.match();if(k==0)cout<<"括號匹配"<<endl;else if(k==1)cout<<"括號不匹配"<<endl;return 0; }總結
- 上一篇: java bean 工厂模式_深入理解J
- 下一篇: 【实用数学手册(第2版)扫描版.pdf】