#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
#define MAXSIZE 20
#define BUFFERSIZE 60
/*
Input : str = “()())()” -
Output : ()()() (())()
There are two possible solutions
"()()()" and "(())()"
Input : str = (v)())()
Output : (v)()() (v())()
*/
//struct node {
// char *data;
// struct node *next;
//};
//是否是有效字符串
bool isValidParentheses(char input[MAXSIZE]){
int len = strlen(input);
int cnt = 0;
for(int i = 0; i < len; i++){
if(input[i] == '(')
cnt++;
if(input[i] == ')')
cnt--;
if(cnt < 0)
return false;
}
return cnt == 0;
}
bool isParenthesie(char c){
return c == '(' || c == ')';
}
//效率不高
void removeBottom(char *queue[BUFFERSIZE], int queueSize){
free(queue[0]);
queue[0] = NULL;
queueSize = queueSize - 1;
//从第二位开始前移,用以模仿链表
for(int i = 0;i < queueSize; i++){
if(queue[i] == NULL)
queue[i] = (char *)malloc(sizeof(char)*MAXSIZE);
strcpy(&queue[i][0], &queue[i+1][0]);
}
//将最后一位置空
if(queue[queueSize] != NULL){
free(queue[queueSize]);
queue[queueSize] = NULL;
}
}
//已验证过字符串的栈,是否包含该字符串,用以排除重复
bool notContent(char *visit[BUFFERSIZE], char *input, int visitSize){
for(int i = 0; i < visitSize; i++){
if(strstr(visit[i], input) != NULL)
return false;
}
return true;
}
//删除无效字符串
//Breadth first search
void removeInvalidParenthese(char input[MAXSIZE]){
if(*input == '\0')
return ;
char *queue[BUFFERSIZE];
char *visit[BUFFERSIZE];
//queueSize广度优先遍历里的栈
int queueSize = 1;
//已验证过字符串的栈
int visitSize = 1;
queue[0] = (char *)malloc(sizeof(char)*MAXSIZE);
strcpy(&queue[0][0], &input[0]);
visit[0] = (char *)malloc(sizeof(char)*MAXSIZE);
strcpy(&visit[0][0], &input[0]);
int level = false;
while(queueSize > 0){
char str[MAXSIZE];
//拷贝并删除第一个位
strcpy(&str[0], &queue[0][0]);
//实现linked List 的 remove功能
//移除最底端的元素,最先入栈的元素
removeBottom(queue, queueSize);
queueSize--;
//在这个层级(删除n个'('或')'后)为有效括号表达式
if(isValidParentheses(str)){
printf("%s\n",str);
level = true ;
}
//当到达某个层级后(即删除n个括号后)为有效括号表达式,
//则在该层级遍历即可,即 只查找删除n个括号的表达式
if(level)
continue;
int len = strlen(str);
for(int i = 0; i < len; i++){
if(!isParenthesie(str[i]))
continue ;
char del[MAXSIZE];
strcpy(&del[0], &str[0]);
strcpy(&del[i], &str[i + 1]);
if(notContent(visit, del, visitSize)){
queue[queueSize] = malloc(sizeof(char)*MAXSIZE);
strcpy(&queue[queueSize][0], &del[0]);
//保存已验证过的字符串
visit[visitSize] = (char *)malloc(sizeof(char)*MAXSIZE);
strcpy(&visit[visitSize][0], &del[0]);
queueSize++;
visitSize++;
}
}
}
}
int main(){
//不能处理大于MAXSIZE的数据
char input[MAXSIZE] = "(v)())()";
removeInvalidParenthese(input);
return 0;
}
Invalid Parentheses
猜你喜欢
转载自blog.csdn.net/s15948703868/article/details/107359257
今日推荐
周排行