• 利用哈希表的原理,找到一个字符串中第一次出现的一次的字符


     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <stdlib.h>
     4 
     5 char checkFirstChar(char *stringSrc)
     6 {
     7     char *ptr = stringSrc;
     8     int arraryHash[255];
     9     memset(arraryHash,0,sizeof(int)*255);
    10     while (*ptr != '\0')
    11     {
    12         arraryHash[*ptr]++;
    13         ptr++;
    14     }
    15     int index = 0;
    16     while (index < 255)
    17     {
    18         if (arraryHash[index] == 1)
    19             return (char)index;
    20         index++;
    21     }
    22 }
    23 
    24 int main(int argc, char *argv[])
    25 {
    26     char *sourceString = "abcdabce";
    27     printf("%c\n",checkFirstChar(sourceString));
    28     return 0;
    29 }

    今天在看一道C语言编程题。

    哈希表Hash也称散列表,是根据关键码值key value而直接进行访问的数据结构。即,它通过把关键码值隐射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫散列表。

    定义hash表和基本数据结点:

     1 typedef struct Node
     2 {
     3     int data;
     4     struct Node * next;
     5 }Node;
     6 
     7 typedef struct HashTable
     8 {
     9     Node *value[10];
    10 }HashTable;

    创建一个Hash表:

    1 HashTable *CreateHashTable()
    2 {
    3     HashTable *pHashTbl = (HashTable *)malloc(sizeof(HashTable));
    4     memset(pTH, 0, sizeof(HashTable));
    5     return pHashTbl
    6 }

    找出一个字符串中第一个只出现一次的字符。

    分析:利用和哈希表的原理差不多的思路,就是创建一个表,储存每个字符出现的次数,然后遍历这个表直到找到第一次出现的一次的那个字符。

    关于哈希表的大小,因为ASCII表的大小是255,因此数组的长度为255(arrayHash[255])

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char checkFirstChar(char *stringSrc)
    {
    	char *ptr = stringSrc;
    	int arraryHash[255];
    	memset(arraryHash,0,sizeof(int)*255);
    	while (*ptr != '\0')
    	{
    		arraryHash[*ptr]++;
    		ptr++;
    	}
    	int index = 0;
    	while (index < 255)
    	{
    		if (arraryHash[index] == 1)
    			return (char)index;
    		index++;
    	}
    }
    
    int main(int argc, char *argv[])
    {
    	char *sourceString = "abcdabce";
    	printf("%c\n",checkFirstChar(sourceString));
    	return 0;
    }
    
  • 相关阅读:
    GridControl 选择列、复选框全选(上)
    iOS开发隐藏键盘方法总结
    Leetcode:remove_duplicates_from_sorted_list
    新版的Spring4X怎样下载
    leetcode 242: Valid Anagram
    最简单的基于FFMPEG的Helloworld程序
    电子商务系统的设计与实现(十):DWZ框架与第三方分页组件整合
    电子商务系统的设计与实现(十):DWZ框架与第三方分页组件整合
    电子商务系统的设计与实现(九):后端管理系统功能细化
    电子商务系统的设计与实现(九):后端管理系统功能细化
  • 原文地址:https://www.cnblogs.com/zhou2011/p/2662817.html
Copyright © 2020-2023  润新知