Skip to content

Commit 1ef13ec

Browse files
authored
Create 1160_Find_Words_That_Can_Be_Formed_by_Characters.java
1 parent d08c300 commit 1ef13ec

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// id: 1160
2+
// Name: Find Words That Can Be Formed by Characters
3+
// link: https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
4+
// Difficulty: Easy
5+
6+
class Solution {
7+
int [] map = new int[26];
8+
int [] wordMap;
9+
public int countCharacters(String[] words, String chars) {
10+
for (int i = 0; i < chars.length(); i++) {
11+
map[chars.charAt(i)-'a']++;
12+
}
13+
14+
int result = 0;
15+
for (String word: words) {
16+
if (matches(word)) {
17+
result += word.length();
18+
}
19+
}
20+
21+
22+
return result;
23+
}
24+
25+
private boolean matches (String word) {
26+
wordMap = new int[26];
27+
28+
for (int i = 0; i < word.length(); i++) {
29+
int c = word.charAt(i) - 'a';
30+
wordMap[c]++;
31+
if (wordMap[c]>map[c]) return false;
32+
}
33+
34+
return true;
35+
}
36+
}

0 commit comments

Comments
 (0)