问题很简单:
就是很简单的匹配‘[{()}]'是否匹配,我就试着使用栈的方式解决,可问题很大。代码如下,自己还属于菜鸟,希望大神不要嘲笑了。
#include<iostream>
#include<stack>
using namespace std;
bool seqIsValid(const char*);
char seqRight(char);
bool seqIsValid(const char *str){
stack<char> strStack;
for(;*str != '\0';str++){
if(!strStack.top()){
if(seqRight(strStack.top()) != *str){
strStack.push(*str);
}else{
strStack.pop();
}
}else{
strStack.push(*str);
}
}
if(!strStack.top()){
return false;
}
return true;
}
char seqRight(char ch){
switch(ch){
case '[':
return ']';
case '{':
return '}';
case '(':
return ')';
default:
return '\0';
}
}
int main(){
const char* test = "[{()}]";
if(seqIsValid(test)){
cout<<"seq is valid;"<<endl;
}else{
cout<<"is not valid"<<endl;
}
}
运行结果:
➜ tmp ./test
[1] 31495 segmentation fault ./test
搞定:
#include<iostream>
#include<stack>
using namespace std;
bool seqIsValid(const char*);
char seqRight(char);
bool seqIsValid(const char *str){
stack<char> strStack;
for(;*str != '\0';str++){
if(!strStack.empty()){
if(seqRight(strStack.top()) != *str){
strStack.push(*str);
}else{
strStack.pop();
}
}else{
strStack.push(*str);
}
}
if(!strStack.empty()){
return false;
}
return true;
}
char seqRight(char ch){
switch(ch){
case '[':
return ']';
case '{':
return '}';
case '(':
return ')';
default:
return '\0';
}
}
int main(){
const char* test = "[{()}]";
if(seqIsValid(test)){
cout<<"seq is valid;"<<endl;
}else{
cout<<"is not valid"<<endl;
}
}
if (!strStack.empty())