日常刷题中🐵
目录
GitHub链接😆
diwei00 (github.com)https://github.com/diwei00
刷题代码都在Exercise库中提交
LeetCode链接😉
1002. 查找共用字符 - 力扣(LeetCode)https://leetcode.cn/problems/find-common-characters/
题目 😯
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例1:
输入:words = ["bella","label","roller"] 输出:["e","l","l"]示例2:
输入:words = ["cool","lock","cook"] 输出:["c","o"]
题目解析😆
题目要求需要我们找到每个字符串共有的字符,很容易理解就是找它们的交集。
我们采用桶计数法,先对第一个字符串中的每个字符进行计数,然后在对剩下的字符串中的字符计数。进行对比,交集那肯定是每个字母个数的最小值,不断的去更新第一次对字符串的计数。这样一来,当我们遍历完所有字符串后,就存储了字符在所有字符串中出现次数的最小值。最后在倒出为字符串数组。
由于题目中提到所有字母都是小写字母,因此可以用长度为26的数组来计数。
注意:
🎈倒出为字符串数组时,需要我们开辟一个char**的数组,用来存放每个字符串的首字符地址,那么每个字符串也需要相应的内存空间,这个char**的数组只是存储了它们的首字符地址,所以在倒字符串时,也需要对每个字符串开辟相应的内存空间。
🎈在引用字符串数组中每个字符时,要保证其优先级。例如:(*(words + i))[j] ,需要让word + i先和*结合,这样才为cha* 类型,然后才可以认为*(words + i)为char**数组内某个字符串的首字符地址。接下来再访问某个字符串中的字符。
代码实现(有详细注释)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** commonChars(char** words, int wordsSize, int* returnSize)
{
int* minPa = (int*)malloc(sizeof(int) * 26);
memset(minPa, 0, sizeof(int) * 26);
int* pa = (int*)malloc(sizeof(int) * 26);
memset(pa, 0, sizeof(int) * 26);
int sz = 26;
int len = strlen(words[0]);
//桶计数法,统计第一个字符串个数
int i = 0;
for (i = 0; i < len; i++)
{
minPa[(*words)[i] - 'a']++;
}
for (i = 1; i < wordsSize; i++)
{
int j = 0;
while ((*(words + i))[j] != '\0')
{
pa[(*(words + i))[j] - 'a']++;
j++;
}
//更新为最小值
for (j = 0; j < sz; j++)
{
if (pa[j] < minPa[j])
{
minPa[j] = pa[j];
}
}
//初始化pa,再次进行计数
memset(pa, 0, sizeof(int) * 26);
}
//倒数据
char** ppa = (char**)malloc(sizeof(char*) * 100);
int index = 0;
for (i = 0; i < sz; i++)
{
if (minPa[i] != 0)
{
int flag = minPa[i];
while (flag--)
{
ppa[index] = (char*)malloc(sizeof(char) * 2);
(*(ppa + index))[0] = i + 'a';
(*(ppa + index))[1] = 0;
index++;
}
}
}
*returnSize = index;
return ppa;
}
int main()
{
char* arr[] = { "bella","label","roller" };
int sz = sizeof(arr) / sizeof(arr[0]);
int num = 0;
char** pa = commonChars(arr, sz, &num);
int i = 0;
for (i = 0; i < num; i++)
{
printf("%s\n", pa[i]);
}
return 0;
}
小结😊
不同的算法效率差距是非常大的,可见算法的优化是多么的重要,所以需要我们大量的去刷题,锻炼我们的编程思维,同时多去学习优秀的算法,相信坚持下去会有不一样的收获。