从基于C ASCII字符检测最频繁发生的象征 [英] Detecting most frequently recurring symbol from ASCII-characters on C

查看:96
本文介绍了从基于C ASCII字符检测最频繁发生的象征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何写的作为输入的ASCII字符序列,并给出了最经常反复出现的符号的功能的实现?我需要做它放在C,我哪里不好?

How do I write an implementation for a function that takes as input a sequence of ASCII-characters, and gives the most frequently recurring symbol? I need make it on C, Where my bad?

  char mostFrequentCharacter(char* str, int size);



 char value;
 int valueCount = 0;
 for (int i =0; i < strlen(str); i++)
 {
       char oneChar = str[i];
       var totalCount = source.Split(oneChar).Length - 1;;
      if (totalCount >= valueCount)
      {
       valueCount = totalCount;
       value = oneChar;
      }
 }
  return value;

要优化的功能,与双核心基于ARM的处理器和内存无限量的设备上运行。

The function to be optimized to run on a device with a dual-core ARM-based processors and infinite amount of memory.

推荐答案

如果内存并不如你所指出的,那么你768,16创建查找表,你将存储OCCURENCES的数量为每个字符的问题。因为输入是ASCII字符序列,结构的尺寸应256检查输入和初始化查找表,在主循环之后,增加在查找表中的相应位置OCCURENCES的数目,检查是否超过了出现的次数当前最大计数,如果是,更新当前最大计数和当前最常见的字符。最后,只返回最常见的字符。此解决方案复杂度为O(N)和空间复杂度为O(1)。

If the memory is not an issue as you noted, then you shoud create lookup table where you will store number of occurences for each character. Since input is sequence of ASCII characters, size of the structure should be 256. After checking input and initializing lookup table, in the main for loop, increment number of occurences in the corresponding place in the lookup table, check if the number of occurences exceeded the current maximal count, if so, update current maximal count and current most frequent character. In the end, just return most frequent character. Time complexity of this solution is O(N) and space complexity O(1).

char mostFrequentCharacter(char* str, int size) {
    char mosfFrequent;
    int counts[256], i, maxCount = 0;

    // in the case of invalid input, return some invalid character
    if(!str || size < 1)
        return '\0';

    for(i = 0; i < 256; i++)
        counts[i] = 0;

    for (i = 0; i < size; i++)
    {
        counts[str[i]]++;

        if(counts[str[i]] > maxCount) {
            maxCount = counts[str[i]];
            mostFrequent = str[i];
        }
    }
    return mostFrequent;
}

这篇关于从基于C ASCII字符检测最频繁发生的象征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆