zoukankan      html  css  js  c++  java
  • C/C+面试题一:找出字符串中出现最多的字符和次数,时间复杂度小于O(n^2)

    已知字符串“aabbbcddddeeffffghijklmnopqrst”编程找出出现最多的字符和次数,要求时间复杂度小于O(n^2)

    /********************************************************
    Copyright (C), 2016-2017,
    FileName: 	main9
    Author: 	woniu201
    Email: 		wangpengfei.201@163.com
    Created: 	2017/10/31
    Description:求字符串中出现次数最多的字符和次数
    ********************************************************/
    #include "stdafx.h"
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void search(char* pData, int len)
    {
    	char counts[1024] = {0};    //存放原始数据作为为索引出现的次数
    	char bufMax[1024] = {0};    //用于存放出现次数最多的字符
    	int max = 0;			    //出现次数最多的字符
    
    	for (int i=0; i<len; i++)
    	{
    		counts[pData[i]] ++;
    	}
    
    	for (int i=0; i<1024; i++)
    	{
    		if (counts[i] > max)
    		{
    			max = counts[i];
    			bufMax[0] = i;
    		}else if ((counts[i] == max) && (counts[i] !=0))
    		{
    			bufMax[strlen(bufMax)] = i;
    		}
    	}
    
    	printf("出现最多的字符分别为:");
    	for (int i=0; i<strlen(bufMax); i++)
    	{
    		printf("%c ", bufMax[i]);
    	}
    	printf("
    ");
    	printf("出现最多的字符的次数:%d
    ", max);
    }
    
    int main()
    {
    	char* srcData = "aabbbcddddeeffffghijklmnopqrst";
    
    	search(srcData, strlen(srcData));
    	getchar();
    	return 1;
    }

    欢迎加群交流:C/C++开发交流

  • 相关阅读:
    dict
    list & tuple
    int & bool & string
    关于gcc内置的原子操作函数
    关于quicklz压缩算法在游戏中的应用
    为mingw生成mysql的客户端库文件
    linux下core生成与调试
    linux下GCC编译动态库切记加 -fPIC
    一则gvim命令
    WIN系统下网络莫名其妙怪异的无法可用时的处理方式
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694590.html
Copyright © 2011-2022 走看看