首页 > 解决方案 > 如何获得单词中出现频率最高的字母?

问题描述

我正在尝试获取字符串中最常见的字母,其中只有大写字母,单词之间没有空格。为此,我使用了一个函数,该函数maxArray(array, sizeof array)给出数组中的最大数字,以计算字母重复的次数,并将信息存储在另一个数组中字符串中每个字母的相同位置。但是在我提出的两种算法中它不起作用。

PS:我只是一个初学者。

这是代码:

int maxArray(int *tab, int n) {
    int i, tmp;
    tmp = tab[0];
    for (i = 1; i < n; i++) {
        if (tmp < tab[i])
            tmp = tab[i];
    }
    return tmp;
}

//first algo(didn't finish it)

char occurencedelettre(char *string) {
    int *array;
    int i, j, compt, max;
    for (i = 0; string[i] !='\0'; i++) {
        compt = 0;
        for (j = 0; string[j] !='\0'; j++) {
            if (string[i] == string[j])
                compt++;
        }
        array[i] = compt;    
    }
    return array;
}

//second one
char occurencedelettre(char *string) {
    int count[25] = { 0 };
    int x = 0;  
    char result;   
    for (int i = 0; string[i] != '\0'; i++) { 
        count[string[i]]++; 
        if (x < count[string[i]]) { 
            x = count[string[i]]; 
            result = string[i]; 
        } 
    } 
    return result;
}    

标签: c

解决方案


第二种方法几乎是正确的,除了这些问题:

  • 数组的长度应为 26
  • 您必须'A'从字母的值中减去 和 之间的索引025假设该单词仅包含 ASCII 中的大写字母。
  • 您必须初始化result以返回0(或任何其他特定值)空字。

这是修改后的版本:

char occurencedelettre(const char *string) {
    size_t count[26] = { 0 };
    size_t x = 0;  
    char result = '\0';   
    for (size_t i = 0; string[i] != '\0'; i++) { 
        count[string[i] - 'A']++; 
        if (x < count[string[i]]) { 
            x = count[string[i]]; 
            result = string[i]; 
        } 
    } 
    return result;
}    

第一种方法更麻烦、更慢,但也更通用,因为它可能适用于任何单词内容。这是修改后的版本:

char occurencedelettre(const char *string) {
    char result = 0;
    size_t max_count = 0;
    for (size_t i = 0; string[i] != '\0'; i++) {
        size_t count = 1;
        for (size_t j = i + 1; string[j] != '\0'; j++) {
            if (string[i] == string[j])
                count++;
        }
        if (max_count < count) {
            max_count = count;
            result = string[i];
        }
    }
    return result;
}

请注意,您可以针对任何字内容调整第一种方法,假设为 8 位字节:

char occurencedelettre(const char *string) {
    size_t count[256] = { 0 };
    size_t x = 0;  
    char result = '\0';   
    for (size_t i = 0; string[i] != '\0'; i++) { 
        count[(unsigned char)string[i]]++; 
        if (x < count[(unsigned char)string[i]]) { 
            x = count[(unsigned char)string[i]]; 
            result = string[i]; 
        } 
    } 
    return result;
}    

推荐阅读