题目:给定一个只包括 '(',')','{','}','[',']'的字符串 s ,判断字符串是否有效。有效字符串需满足:左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。
思路:使用栈来解决,与判断回文串的道理相同。
bool isValid(char* str){
stack<char> s;
for(int i = 0; i < strlen(str); i ++){
if(str[i] == '(')
s.push(')');
else if(str[i] == '{')
s.push('}');
else if(str[i] == '[')
s.push(']');
//出现单独的右括号||左右括号不匹配
else if(s.empty() || s.top() != str[i])
return false;
//若没有出现上述情况则括号匹配,直接出栈
else s.pop();
}
return s.empty();
}
全部代码:
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
bool isValid(char* str){
stack<char> s;
for(int i = 0; i < strlen(str); i ++){
if(str[i] == '(')
s.push(')');
else if(str[i] == '{')
s.push('}');
else if(str[i] == '[')
s.push(']');
//出现单独的右括号||左右括号不匹配
else if(s.empty() || s.top() != str[i])
return false;
//若没有出现上述情况则括号匹配,直接出栈
else s.pop();
}
return s.empty();
}
int main(){
char str1[] = "{}[](){[()]}";
char str2[] = "{
{
{
{}}[][][][)";
cout<<str1;
cout<<"是有效括号吗?"<<isValid(str1)<<endl;
cout<<str2;
cout<<"是有效括号吗?"<<isValid(str2)<<endl;
}
运行结果:
更多代码请参考:手撕考研数据结构(代码汇总)