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