Find Words That Can Be Formed by Characters LeetCode solution in Java

1
class Solution {
2
public int countCharacters(String[] words, String chars) {
3
int[] freq = new int[26];
4
for (int i = 0; i < chars.length(); i++) {
5
// char - char is a kind of clever way to get the position of
6
// the character in the alphabet. 'a' - 'a' would give you 0.
7
// 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on.
8
freq[chars.charAt(i) - 'a']++;
9
}
10

11
int result = 0;
12
for (String word : words) {
13
int[] copy = Arrays.copyOf(freq, freq.length);
14
boolean pass = true;
15
for (int j = 0; j < word.length(); j++) {
16
// decrement the frequency of this char in array for using
17
// if there are less than 1 chance for using this character, invalid,
18
// move to next word in words
19
if (--copy[word.charAt(j) - 'a'] < 0) {
20
pass = false;
21
break;
22
}
23
}
24
if (pass) {
25
result += word.length();
26
}
27
}
28
return result;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0