1805过来的。可以提取出解题框架了:
[题目类型]:从句子中,单词之间各种操作;返回符合条件的单词,或个数; [框架]:
void GetWord (char *input, int *in)
{
int left = *in;
int right = *in;
while (isalpha(input[right])) { // isdigit(input[right])
right++;
}
right--;
// 处理前导、末尾空格 / 0、多余标点等
*in = right;
}
int / char * Function (char *input, other arv)
{
int index = 0;
int cnt = 0;
while (input[index] != NULL) {
if (condition1 / condition1(input)) {
GetWord(input, &index, ...);
// if (condition2)
UpdateWordCnt(input, &cnt);
}
index++;
}
}
题解:
#define MAX_NUM 1001
typedef struct {
char str[MAX_NUM];
int cnt;
UT_hash_handle hh;
} WordHash;
WordHash *g_hashTbl = NULL;
void GetWord (char *para, int *in, char *word)
{
int left = *in;
int right = *in;
while (isalpha(para[right])) {
//printf("para[%d] = %c\n", right, para[right]);
para[right] =(para[right] >= 'A' && para[right] <= 'Z') ? para[right] - 'A' + 'a' : para[right];
//printf("trans-para[%d] = %c\n", right, para[right]);
right++;
}
right--;
strncpy(word, para + left, right - left + 1);
word[right - left + 1] = '\0';
printf("word = %s\n", word);
*in = right;
return;
}
bool IsBanned (char *word, const char **banned, int bannedSize)
{
for (int i = 0; i < bannedSize; i++) {
if (strcmp(word, banned[i]) == 0) {
return true;
}
}
return false;
}
void UpdateWordCnt(char *word)
{
WordHash *tmp = NULL;
HASH_FIND_STR(g_hashTbl, word, tmp);
if (tmp == NULL) {
tmp = (WordHash *)calloc(1, sizeof(WordHash));
strcpy(tmp->str, word);
tmp->cnt++;
HASH_ADD_STR(g_hashTbl, str, tmp);
} else {
tmp->cnt++;
}
return;
}
int cmp (const void *a, const void *b)
{
WordHash *aa = (WordHash *)a;
WordHash *bb = (WordHash *)b;
return bb->cnt - aa->cnt;
}
char * mostCommonWord(char * paragraph, const char ** banned, int bannedSize){
int index = 0;
static char word[MAX_NUM];
g_hashTbl = NULL;
while (paragraph[index] != '\0') { // 自动滤掉前导空格、标点
if (isalpha(paragraph[index])) {
GetWord(paragraph, &index, word);
//printf("word = %s\n", word);
if (!IsBanned(word, banned, bannedSize)) {
UpdateWordCnt(word);
}
}
index++;
}
HASH_SORT(g_hashTbl, cmp);
WordHash *table;
for (table = g_hashTbl; table != NULL; table = table->hh.next) {
strcpy(word, table->str);
return word;
}
return word;
}
作者:Crystal
链接:https://leetcode.cn/problems/most-common-word/solutions/2100676/c-ha-xi-biao-ge-chong-yong-by-crystal-8k-upjn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。