赞
踩
- 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
-
- 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
-
- 注意:每次拼写时,chars 中的每个字母都只能用一次。
-
- 返回词汇表 words 中你掌握的所有单词的 长度之和。
-
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 示例 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。
-
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

- 提示:
-
- 1、1 <= words.length <= 1000
- 2、1<= words[i].length, chars.length <= 100
- 3、所有字符串中都仅包含小写英文字母
-
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
先统计会的字母的个数,用一个26个的数组表示;再遍历每一个单词,统计其中的字母出现的次数;遍历26个索引,如果这个单词的次数有小于统计的次数的,那么就舍弃这个单词,统计下一个单词的字母出现次数;直到有一个单词的字母出现次数小于等于总的次数,这时候res加上这个单词的长度。
代码
- class Solution {
- public:
- //初步思路 创建一个数组统计chars里面每一个字符出现的次数;遍历每一个单词,如果每一个的字母的次数都>=1那么最后加上这个单词的长度。
- int countCharacters(vector<string>& words, string chars) {
- int times[26]={0};
- for(auto i=0;i<chars.size();i++)
- {
- times[(int)chars[i]-'a']++;
- }
- int res=0;//统计总的次数
-
- for(int i=0;i<words.size();i++)
- {
- int flag=1;
- int time_temp[26]={0};
- for(int j=0;j<words[i].size();j++)
- {
- time_temp[(int)words[i][j]-'a']++;
-
- }
- for(int i=0;i<26;i++)
- {
- if(time_temp[i]>times[i])
- {flag=0;break;}
- }
- //对刚刚通过的单词的字母次数减1
- if(flag==1)
- {
- // for(int j=0;j<words[i].size();j++)
- // {
- // // times[(int)words[i][j]-'a']--;
- // res++;
- // }
- res+=words[i].size();
- }
- }
- return res;
-
- }
- };

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。