C语言最长字符串链,LeeCode-1048-最长字符串链-C语言

/* check two words can be word chain by hash table */

bool check(int num, int start, int end, int arr[num][26]){

int i;int flag = 0;

for(i=0; i<26; i++){

if(arr[end][i] == arr[start][i]){

continue;

}else if(arr[end][i] == arr[start][i]+1){

if(flag == 0){

/* find different first time */

flag = 1;

}else{

/* had found different yet */

return false;

}

}else if(arr[end][i] >= arr[start][i]+1 || arr[end][i] < arr[start][i]){

return false;

}

}

/* flag means different, else means same */

if(flag)

return true;

else

return false;

}

void print_arr(int *arr, int len){

int i;

for(i=0; i

printf("%d,", arr[i]);

printf("\n");

}

/* dfs to vist index position word */

void dfs(char **words, int num, int index, int len, int arr[num][26], int *max, int *vst){

int i;

/* if current word is visited or index is invalid, return */

if(index>= num || vst[index])

return;

for(i=0; i

if(i==index || !check(num, index, i, arr)){

continue;

}

vst[index] = 1;

len++;

if(len > (*max)){

*max = len;

}

/* at this point, words at index and i can be word chain, so we try i */

dfs(words, num, i, len, arr, max, vst);

len--;

vst[index] = 0;

}

}

int longestStrChain(char ** wds, int wnum){

if(wnum == 1) return 1;

int arr[wnum][26]; int i,j;

memset(arr, 0, sizeof(arr));

/* mapping words to hash_table */

for(i=0; i

for(j=0; wds[i][j] != '\0'; j++){

arr[i][wds[i][j]-'a']++;

}

}

int max = 0;

int tmp = 1;

int vst[wnum];

for(i=0; i

tmp = 0;

memset(vst, 0, sizeof(vst));

dfs(wds, wnum, i, 0, arr, &tmp, vst);

if(tmp > max){

max = tmp;

}

}

return max+1;

}

你可能感兴趣的:(C语言最长字符串链)