c++括号匹配
时间: 2023-07-01 12:26:10 浏览: 81
括号匹配是一个经典的问题,可以使用栈来解决。
具体思路如下:
1. 遍历字符串中的每个字符。
2. 如果当前字符是左括号,将其推入栈中。
3. 如果当前字符是右括号,判断栈是否为空。如果为空,说明缺少左括号,括号不匹配。如果栈不为空,弹出栈顶元素,判断其是否与当前右括号匹配。如果不匹配,括号不匹配。
4. 遍历完所有字符后,如果栈中还有元素,说明括号不匹配。
下面是C++代码实现:
```c++
#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool check(string s){
stack<char> st;
for(int i=0;i<s.length();i++){
if(s[i]=='('||s[i]=='['||s[i]=='{'){
st.push(s[i]);
}
else if(s[i]==')'||s[i]==']'||s[i]=='}'){
if(st.empty()){
return false; //缺少左括号,不匹配
}
char c=st.top();
st.pop();
if((s[i]==')'&&c!='(')||(s[i]==']'&&c!='[')||(s[i]=='}'&&c!='{')){
return false; //左右括号不匹配,不匹配
}
}
}
if(!st.empty()){
return false; //还有左括号未匹配,不匹配
}
return true; //匹配
}
int main(){
string s;
cin>>s;
if(check(s)){
cout<<"括号匹配"<<endl;
}
else{
cout<<"括号不匹配"<<endl;
}
return 0;
}
```