2781. 最长合法子字符串的长度
C代码:滑动窗口、哈希表
typedef struct{
char* str;
UT_hash_handle hh;
} HashTable;
HashTable* head;
void AddToHash(char* str) {
HashTable* out = (HashTable*)malloc(sizeof(HashTable));
out->str = str;
HASH_ADD_STR(head, str, out);
}
bool FindStr(char* word, int r, int j) {
HashTable* out = NULL;
char* str = (char*)malloc(sizeof(char) * 11);
str[0] = '\0';
strncat(str, word + j, r - j + 1);
HASH_FIND_STR(head, str, out);
return out != NULL;
}
int longestValidSubstring(char * word, char ** forbidden, int forbiddenSize){
head = NULL;
for (int i = 0; i < forbiddenSize; ++i) {
AddToHash(forbidden[i]);
}
int len = strlen(word);
int l = 0;
int ans = 0;
for (int r = 0; r < len; ++r) {
for (int j = r; j >= fmax(l, r - 10 + 1); --j) {
if (FindStr(word, r, j)) {
l = j + 1;
break;
}
}
if (r >= l) {
ans = fmax(ans, r - l + 1);
}
}
return ans;
}