LeetCode //C - 1002. Find Common Characters

张开发
2026/4/3 13:00:51 15 分钟阅读
LeetCode //C - 1002. Find Common Characters
1002. Find Common CharactersGiven a string array words, returnan array of all characters that show up in all strings within the words (including duplicates).You may return the answer in any order.Example 1:Input:words [“bella”,“label”,“roller”]Output:[“e”,“l”,“l”]Example 2:Input:words [“cool”,“lock”,“cook”]Output:[“c”,“o”]Constraints:1 words.length 1001 words[i].length 100words[i] consists of lowercase English letters.From: LeetCodeLink: 1002. Find Common CharactersSolution:Ideas:Since all characters are lowercase English letters, we only need an array of size 26.Count character frequency for the first word.For each remaining word:Count its character frequencies.Take the minimum frequency for each character.The remaining frequencies represent characters common to all words.Build the result array including duplicates.Code:char**commonChars(char**words,intwordsSize,int*returnSize){intminFreq[26]{0};// Initialize with first word frequenciesfor(inti0;words[0][i]!\0;i){minFreq[words[0][i]-a];}// Compare with remaining wordsfor(inti1;iwordsSize;i){intfreq[26]{0};for(intj0;words[i][j]!\0;j){freq[words[i][j]-a];}for(intk0;k26;k){if(freq[k]minFreq[k]){minFreq[k]freq[k];}}}// Count total common charactersinttotal0;for(inti0;i26;i){totalminFreq[i];}*returnSizetotal;char**result(char**)malloc(sizeof(char*)*total);intindex0;for(inti0;i26;i){while(minFreq[i]0){result[index](char*)malloc(sizeof(char)*2);result[index][0]ia;result[index][1]\0;index;minFreq[i]--;}}returnresult;}

更多文章