括號匹配算法
阿新 • • 發佈:2017-09-21
一個 i++ har 出棧 問題 string || mes name
括號匹配,算是字符串處理中的一個問題,比較常見,這裏就總結一下大體的思路,附贈我的個人代碼。
大體思路:數據結構選用棧,讀到左括號時入棧,讀到右括號時判斷是否匹配,匹配則左括號出棧,非括號字符則繼續往下讀
代碼如下:
1 #include <iostream>
2 #include <cstring>
3 #include <string>
4 #include <stack>
5
6 using namespace std;
7 bool is_Match(string str){
8 stack<char> s;
9 for(int i=0;i<str.length();i++){
10 switch(str[i])
11 {
12 case ‘{‘:
13 case ‘[‘:
14 case ‘<‘:s.push(str[i]);break;
15 case ‘}‘:
16 case ‘]‘:
17 case ‘>‘:char temp=str[i];
18 if((!s.empty())&&(temp==‘ }‘&&s.top()==‘{‘)||(temp==‘]‘&&s.top()==‘[‘)||(temp==‘>‘&&s.top()==‘<‘)){
19 s.pop();
20 }
21 else{
22 cout<<"括號不匹配"<<endl;
23 return false;
24 }
25 }
26 }
27 if(!s.empty()){
28 return false;
29 }
30 else{
31 return true;
32 }
33 }
34
35 int main()
36 {
37 bool ans=is_Match("<,34342}>");
38 cout<<ans<<endl;
39 }
括號匹配算法