ascii可见字符(统计字符串出现的频率)

ASCII可见字符

这个应该十分的熟悉,甚至是背下来。

// 32 - 126 的可见字符
const char kASCII[95] = {' ', '!', '"', '#', '$', '%', '&', ''', // 32-39
                         '(', ')',  '*', '+', ',', '-', '.',  '/', // 40-47
                         '0', '1',  '2', '3', '4', '5', '6',  '7', // 48-55
                         '8', '9',  ':', ';', '<', '=', '>',  '?', // 56-63
                         '@', 'A',  'B', 'C', 'D', 'E', 'F',  'G', // 64-71
                         'H', 'I',  'J', 'K', 'L', 'M', 'N',  'O', // 72-79
                         'P', 'Q',  'R', 'S', 'T', 'U', 'V',  'W', // 80-87
                         'X', 'Y',  'Z', '[', '\',']', '^',  '_', // 88-95
                         '`', 'a',  'b', 'c', 'd', 'e', 'f',  'g', // 96-103
                         'h', 'i',  'j', 'k', 'l', 'm', 'n',  'o', // 104-111
                         'p', 'q',  'r', 's', 't', 'u', 'v',  'w', // 112-119
                         'x', 'y',  'z', '{', '|', '}', '~'        // 120-126
                         };

统计字符出现的频率

输入:AB##CCDDE

输出:

A->1
B->1
#->2
C->2
D->2
E->1

我在一次面试答题中使用了 BST,但是实现得太复杂了。下面这种方法应该是较好的。

#include <iostream>
#include <string>
#include <cassert>
using namespace std;

// 32 - 126 的可见字符
const char kASCII[95] = {' ', '!', '"', '#', '$', '%', '&', ''', // 32-39
                         '(', ')',  '*', '+', ',', '-', '.',  '/', // 40-47
                         '0', '1',  '2', '3', '4', '5', '6',  '7', // 48-55
                         '8', '9',  ':', ';', '<', '=', '>',  '?', // 56-63
                         '@', 'A',  'B', 'C', 'D', 'E', 'F',  'G', // 64-71
                         'H', 'I',  'J', 'K', 'L', 'M', 'N',  'O', // 72-79
                         'P', 'Q',  'R', 'S', 'T', 'U', 'V',  'W', // 80-87
                         'X', 'Y',  'Z', '[', '\',']', '^',  '_', // 88-95
                         '`', 'a',  'b', 'c', 'd', 'e', 'f',  'g', // 96-103
                         'h', 'i',  'j', 'k', 'l', 'm', 'n',  'o', // 104-111
                         'p', 'q',  'r', 's', 't', 'u', 'v',  'w', // 112-119
                         'x', 'y',  'z', '{', '|', '}', '~'        // 120-126
                         };

int* F(string str)
{
  int* num = new int[95];
  assert(num);
  for (int i = 0; i < 95; ++i)
    num[i] = 0;

  int size = str.size();
  for (int j = 0; j < size; ++j)
  {
    num[str[j] - ' '] += 1;
  }
  return num;
}

int main()
{
  string str = " dfasdfadagdsa dHU<>::>::#$%^&*(GFVGDHSJAHDsafHUUHUBNDFSadsa";
  // int size = str.size();
  // cout << "size = " << size << endl;
  int* num = F(str);
  //int count = 0;
  for (int i = 0; i < 95; ++i)
  {
    //count += num[i];
    if (num[i] != 0)
      cout << kASCII[i] << "->" << num[i] << endl;
    else
      continue;
  }
  //cout << "count  = " << count << endl;
  delete [] num;
  return 0;
}