gpt4 book ai didi

c - 存储括号打开和关闭的地址

转载 作者:行者123 更新时间:2023-11-30 21:28:30 24 4
gpt4 key购买 nike

如果用户给我一个任意括号组合的字符串,例如(()()),那么我需要一个程序来检查括号的打开和关闭,并存储打开的地址并按安排的方式分别关闭每个支架。我该怎么做?

最佳答案

如果括号类型是一种,则无需仅通过增加或减少计数器来保存某些内容。

示例如下

#include <stdio.h>
#include <stdbool.h>

bool isBalanceBracket(const char *s){
int count = 0;
for(int i = 0; s[i] ; ++i){
if(s[i] == '(')
++count;
else if(s[i] == ')')
if(--count < 0)
return false;
}
return count == 0;
}

int main(void){
const char *test[] = {
"(()())", ")()(", "()))"
};
for(int i = 0; i < sizeof(test)/sizeof(*test); ++i){
if(isBalanceBracket(test[i]))
printf("%s is OK\n", test[i]);
else
printf("%s is NG\n", test[i]);
}
return 0;
}

关于c - 存储括号打开和关闭的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com