From 20976616179c3960eb14dd3661b5dd8469cda481 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 31 Oct 2021 17:04:12 +0100 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=201002.=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6.md=20C=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 44a02ceb..a8450f29 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -331,6 +331,58 @@ func commonChars(_ words: [String]) -> [String] { } ``` +C: +```c +void updateHashTable(int* hashTableOne, int* hashTableTwo) { + int i; + for(i = 0; i < 26; i++) { + hashTableOne[i] = hashTableOne[i] < hashTableTwo[i] ? hashTableOne[i] : hashTableTwo[i]; + } +} + +char ** commonChars(char ** words, int wordsSize, int* returnSize){ + //用来统计所有字母出现的最小频率 + int hashTable[26] = { 0 }; + //初始化返回的char**数组以及返回数组长度 + *returnSize = 0; + char** ret = (char**)malloc(sizeof(char*) * 100); + + //如果输入数组长度为0,则返回NULL + if(!wordsSize) + return NULL; + + int i; + //更新第一个单词的字母频率 + for(i = 0; i < strlen(words[0]); i++) + hashTable[words[0][i] - 'a']++; + //更新从第二个单词开始的字母频率 + for(i = 1; i < wordsSize; i++) { + //创建新的哈希表,记录新的单词的字母频率 + int newHashTable[26] = { 0 }; + int j; + for(j = 0; j < strlen(words[i]); j++) { + newHashTable[words[i][j] - 'a']++; + } + //更新原哈希表 + updateHashTable(hashTable, newHashTable); + } + + //将哈希表中的字符变为字符串放入ret中 + for(i = 0; i < 26; i++) { + if(hashTable[i]) { + int j; + for(j = 0; j < hashTable[i]; j++) { + char* tempString = (char*)malloc(sizeof(char) * 2); + tempString[0] = i + 'a'; + tempString[1] = '\0'; + ret[(*returnSize)++] = tempString; + } + } + } + return ret; +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)