我正试图让括号匹配。需要匹配的是'()','[]','{}'和'[{}]'应该输出true。我不希望它适用于“[{]}”或“[{}”等情况。虽然,现在我的代码没有为正确的匹配输出yes,即使它应该是真的。
代码(更新):
int booleanBalanceBracket(aStack *theStack){
aStack *balanceStack = NULL;
while(theStack){
if(theStack->token == '[' || theStack->token == '{' || theStack->token == '(')
balanceStack = pushBracket(theStack->token, balanceStack);
else if(theStack->token == ']' || theStack->token == '}' || theStack->token == ')'){
if(balanceStack == NULL)
return 0;
else
balanceStack = popBracket(balanceStack);
}
theStack = theStack->nextItem;
}
if(balanceStack == NULL){
return 1;
}else{
return 0;
}
}
int isMatching(int token1, int token2){
if(token2 == '(' && token1 == ')')
return 1;
else if(token2 == '{' && token1 == '}')
return 1;
else if(token2 == '[' && token1 == ']')
return 1;
else
return 0;
}
答案 0 :(得分:2)
尝试这个简单的算法:
for each char c in the input
if opener
push on stack
else if closer
if stack is empty or doesn't match
return false
else
remove top of stack
return true if stack is empty, else false
这可以稍微优化以避免空堆栈检查,并且通过最初将EOF推入堆栈并将EOF与EOF匹配来避免显式检查EOF。
答案 1 :(得分:0)
您的代码问题就在这一行
balanceStack = popBracket(balanceStack);
没有收到pop获得的值。还需要比较弹出的值。
简单字符串的示例
bool booleanBaranceBracket(const char *s){
static const char *left = "{([";
static const char *right = "})]";
size_t len = strlen(s);
char *p, stack[len];
int sp = -1;
int i;
for(i=0;i<len;++i){
if(p = strchr(left, s[i]))
stack[++sp] = s[i];
else if(p = strchr(right, s[i])){
char ch;
if(sp == -1) return false;
ch = stack[sp--];
if(ch != left[p - right]) return false;
}
}
return sp == -1;
}