Skip to content

Commit bb46ac9

Browse files
committed
拼写单词
1 parent 9b619fa commit bb46ac9

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.leetcode_cn.easy;
2+
/*************拼写单词**************/
3+
4+
import java.util.Arrays;
5+
6+
/**
7+
* 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
8+
*
9+
* 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
10+
*
11+
* 注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
12+
*
13+
* 返回词汇表 words 中你掌握的所有单词的 长度之和。
14+
*
15+
*  
16+
*
17+
* 示例 1:
18+
*
19+
* 输入:words = ["cat","bt","hat","tree"], chars = "atach"
20+
* 输出:6
21+
* 解释:
22+
* 可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
23+
* 示例 2:
24+
*
25+
* 输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
26+
* 输出:10
27+
* 解释:
28+
* 可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
29+
*  
30+
*
31+
* 提示:
32+
*
33+
* 1 <= words.length <= 1000
34+
* 1 <= words[i].length, chars.length <= 100
35+
* 所有字符串中都仅包含小写英文字母
36+
*
37+
*/
38+
public class FindWordsByCharacters {
39+
40+
public int countCharacters(String[] words, String chars) {
41+
42+
int[] arr = new int[26]; // 存放对应字母的个数
43+
int result = 0;
44+
int index;
45+
int[] copyArr; // 拷贝数组
46+
char[] chars1;
47+
for (char c : chars.toCharArray()) {
48+
index = (int) c - 'a';
49+
arr[index] += 1;
50+
}
51+
// 遍历判断
52+
for (String s : words) {
53+
if (s.length() > chars.length())
54+
continue;
55+
chars1 = s.toCharArray();
56+
copyArr = Arrays.copyOf(arr, arr.length);
57+
for (int i = 0; i < chars1.length; i++) {
58+
index = (int) chars1[i] - 'a';
59+
if (copyArr[index] != 0) {
60+
copyArr[index] -= 1;
61+
} else
62+
break;
63+
if (i == chars1.length - 1) {
64+
result = result + s.length();
65+
}
66+
}
67+
}
68+
return result;
69+
}
70+
71+
public static void main(String[] args) {
72+
System.out.println((int) 'a');
73+
System.out.println((int) 'z');
74+
System.out.println((int) 'b'-'a');
75+
}
76+
}

0 commit comments

Comments
 (0)