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;}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2478905.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!