首页 > 其他 > 详细

【剑指offer】拼写单词(每日一题)

时间:2020-03-17 22:39:51      阅读:63      评论:0      收藏:0      [点我收藏+]

题目链接:拼写单词


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

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

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

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

 

题解:暴力。类似hash?用一个数组统计chars的次数,再复制这个数组,每次在words里的word去遍历,出现不相同的就标记。能顺利遍历就记录一下这个word的长度。

 


代码:

 1 class Solution {
 2 public:
 3     int mp[26] = {0};   
 4 
 5     int countCharacters(vector<string>& words, string chars) {
 6         int len = chars.size();
 7         for(int i = 0; i < len; i++){
 8             mp[chars[i] - a]++;
 9         }   //统计
10 
11         int ans = 0;
12         int res[26];    //复制表
13         for(int i = 0; i < words.size(); i++){
14             string word = words[i];
15             memcpy(res,mp,sizeof(mp));
16             int flag = 1;
17             for(int j = 0 ; j < word.size(); j++){
18                 if(res[word[j] - a] == 0){    //如果没有这个字母
19                     flag = 0;
20                     break;
21                 }
22                 else    res[word[j] - a]--;
23             }
24             if(flag)    ans += word.size();
25         }
26 
27         return ans;
28     }
29 };

 

【剑指offer】拼写单词(每日一题)

原文:https://www.cnblogs.com/Asumi/p/12513682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!