0%

拼写单词-LeetCode

拼写单词

拼写单词

1
2
3
4
5
6
7
8
9
10
11
12
13
1160.拼写单词
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。

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

@see https://leetcode-cn.com/problems

Implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class GetChar2 {
public static void main(String[] args) {
String[] words = {"hello","world","leetcode"};
String chars = "welldonehoneyr";
System.out.println(countCharacters(words,chars));
}

//1.统计字母表chars中26个字母个数
//2.统计词汇表中单个词汇words[i]中26个字母个数
//3.单个词汇中字母个数与字母表中字母个数比较
public static int countCharacters(String[] words, String chars) {
//字母表26个字母的个数
int sum = 0;
int[] chars1 = new int[26];
for (char c : chars.toCharArray()) {
chars1[c - 'a']++;
}

for (String str : words) {
int[] chars2 = new int[26];
//每个单词26个字母的个数
for (char strch : str.toCharArray()) {
chars2[strch - 'a']++;
}
//System.out.println(Arrays.toString(chars2));
boolean flag = true;
//比较单词和字母表的26个字母数量的大小
for (int i = 0; i < chars2.length; i++) {
if (chars2[i] > chars1[i]){
flag = false;
break;
}
}
if (flag){
sum += str.length();
}
}
return sum;
}
}