双指针+排序暴力求解
首先对字符串字典中的每个字符串进行排序,这里要用到qsort函数。然后遍历字典,依次拿字典中的字符串和目标字符串s进行比较,这里用到strchr函数,即返回字符串中第一个目标字符的位置,之后对s和字典字符串往后遍历,直到字典字符串全部被比较完,表示符合条件。然后记录此时字典字符串的长度和索引,如果后面还有符合条件且更长的字符串,再更新索引。
#include<stdio.h>
#include<Windows.h>
int compare(char* p, char* s) {
char* s1 = s;
do {
s1 = strchr(s1, *p);//找到字典字符串每个字符第一次在s中出现的位置
if (s1 == NULL) {
return 0;
}
p++;//找到后的位置也要往后++,防止出现字典字符串出现"ssss"这种情况
s1++;
} while (*p != '\0');
return 1;
}
int strcmp1(const void* a, const void* b) {
return strcmp(*(char**)a, *(char**)b);
}
char* findmax(char* s, char** d, int dSize) {
int maxlength = 0;
int maxindex = -1;
qsort(d, dSize, sizeof(char*), strcmp1);//对字典中的每个字符串排序
for (int i = 0; i < dSize; i++) {
if (compare(d[i], s) != 1) {
continue;
}
else {
if (strlen(d[i]) > maxlength) {
maxlength = strlen(d[i]);//更新字典中的索引
maxindex = i;
}
}
}
if (maxindex == -1) {
return "";
}
return d[maxindex];
}