当前位置:   article > 正文

Leetcode 拼写单词_字符串数组["cat""hat""tree"]字典["catah"]

字符串数组["cat""hat""tree"]字典["catah"]

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和。

 

示例 1:

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。

示例 2:

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。


链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters

 

思路:查表法

  1. int countCharacters(char ** words, int wordsSize, char * chars){
  2. int i, j, k;
  3. int count = 0;
  4. int ret = 0;
  5. char tableA[26] = {0};
  6. char tableB[26] = {0};
  7. for(i = 0; chars[i] != '\0'; i++)
  8. tableA[chars[i] - 'a']++;
  9. for(i = 0; i < wordsSize; i++) {
  10. count = 0;
  11. memcpy(tableB,tableA,sizeof(char)*26);
  12. for(j = 0; words[i][j] != '\0'; j++)
  13. if(tableB[words[i][j] - 'a']) {
  14. count++;
  15. tableB[words[i][j] - 'a']--;
  16. }
  17. if(count == j)
  18. ret += j;
  19. }
  20. return ret;
  21. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/705374
推荐阅读
相关标签
  

闽ICP备14008679号