当前位置:网站首页>Bracket matching -- [implementation of one-dimensional array]

Bracket matching -- [implementation of one-dimensional array]

2022-04-23 20:35:00 Anonymous&

Parentheses matching 【 One dimensional array implementation 】

#include<iostream>
#include<string>
#include<stack>

using namespace std;
string st;
bool isLeft(char c)// Determine whether it is an open bracket 
{
    
 if(c=='('||c=='{'||c=='[') return true;
 else return false;
}
bool isSame(char c1,char c2) // Determine whether parentheses are of the same type 
{
    
 if(c1=='('&&c2!=')') return false;
 if(c1=='{'&&c2!='}') return false;
 if(c1=='['&&c2!=']') return false;
 return true;
}

bool isValid(string s)
{
    
 stack<char> b;
 for(int i =0;i<s.length();i++)
 {
    
  if( isLeft(s[i]) ) b.push(s[i]);// If it's left parenthesis , Direct stack 
  else
  {
    
   if(b.size()==0) return false;// Scan to right parenthesis , But the stack is empty , Description: the match was unsuccessful 
   char top = b.top();
   if(!isSame(top,s[i])) return false;// If the current stack top element and the currently scanned parentheses are not of the same type, it indicates that the matching is not successful 
   else
    b.pop();
  }
 }
 if(b.size()==0) return true;// End of scan , The stack is empty, indicating that the brackets match successfully 
 else return false;
}
int main(){
    
 cin>>st;
 if(isValid(st)) 
  cout<<"bracket is valid"<<endl;
 else
  cout<<"bracket is not valid"<<endl;
 return 0;
}

版权声明
本文为[Anonymous&]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210547369363.html