输入一个长度为n的括号序列,是由n/2个前括号和后括号组成的,它有可能不合法,你需要对他进行一些操作来合法。求要几次(c++代码)
时间: 2023-05-10 19:55:15 浏览: 63
可以使用栈来解决这个问题。遍历括号序列,如果遇到前括号就将其入栈,如果遇到后括号就将栈顶的前括号出栈。如果遍历完后栈为空,则说明括号序列合法,否则不合法。
以下是C代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char str[MAX_LEN];
int len, i, cnt = 0;
scanf("%s", str);
len = strlen(str);
if (len % 2 != 0) {
printf("非法括号序列\n");
return 0;
}
for (i = 0; i < len; i++) {
if (str[i] == '(') {
cnt++;
} else if (str[i] == ')') {
if (cnt > 0) {
cnt--;
} else {
printf("非法括号序列\n");
return 0;
}
}
}
if (cnt == 0) {
printf("括号序列合法\n");
} else {
printf("非法括号序列\n");
}
return 0;
}
```
需要的操作次数为O(n),其中n为括号序列的长度。