难度简单95收藏分享切换为英文关注反馈
给你一份『词汇表』(字符串数组) 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。
提示:
1 <= words.length <= 10001 <= words[i].length, chars.length <= 100- 所有字符串中都仅包含小写英文字母
解题思路
友情提示:遇到有提示字符串仅包含小写(或者大写)英文字母的题,
都可以试着考虑能不能构造长度为26的每个元素分别代表一个字母的数组,来简化计算
对于这道题,用数组hash来保存字母表里每个字母出现的次数
如法炮制,再对词汇表中的每个词汇都做一数组map,比较数组map与数组hash的对应位置
如果map中的都不大于hash,就说明该词可以被拼写出,长度计入结果
如果map其中有一个超过了hash,则说明不可以被拼写,直接跳至下一个(这里用到了带label的continue语法)
public class C1160 {
/**
* 解题思路
友情提示:遇到有提示字符串仅包含小写(或者大写)英文字母的题,
都可以试着考虑能不能构造长度为26的每个元素分别代表一个字母的数组,来简化计算
对于这道题,用数组c来保存字母表里每个字母出现的次数
如法炮制,再对词汇表中的每个词汇都做一数组w,比较数组w与数组c的对应位置
如果w中的都不大于c,就说明该词可以被拼写出,长度计入结果
如果w其中有一个超过了c,则说明不可以被拼写,直接跳至下一个(这里用到了带label的continue语法)
* @param words
* @param chars
* @return
*/
public int countCharacters(String[] words, String chars) {
int res=0;
int[] hash = new int[26];
for (char i : chars.toCharArray()) {
hash[i - 'a']++;
}
int[] map = new int[26];
for(String string : words) {
boolean flag = true;
Arrays.fill(map, 0);
for (char ch : string.toCharArray()) {
map[ch - 'a']++;
if (map[ch - 'a'] > hash[ch - 'a']) {
flag = false;
}
}
if (flag) {
res+=string.length();
}
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words = {"cat","bt","hat","tree"};
String chars = "atach";
C1160 c1160 = new C1160();
System.out.println(c1160.countCharacters(words, chars));
}
}
762

被折叠的 条评论
为什么被折叠?



