forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountTheNumberOfConsistentStrings.java
35 lines (31 loc) · 1.05 KB
/
CountTheNumberOfConsistentStrings.java
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
// T: O(allowed + words * word)
// S: O(allowed)
import java.util.HashSet;
import java.util.Set;
public class CountTheNumberOfConsistentStrings {
public int countConsistentStrings(String allowed, String[] words) {
final Set<Character> allowedCharacters = getCharacters(allowed);
int consistentStrings = 0;
for (String word :words) {
if (allCharsPresentIn(word, allowedCharacters)) {
consistentStrings++;
}
}
return consistentStrings;
}
private Set<Character> getCharacters(String string) {
final Set<Character> set = new HashSet<>();
for (int index = 0 ; index < string.length() ; index++) {
set.add(string.charAt(index));
}
return set;
}
private boolean allCharsPresentIn(String string, Set<Character> allowedChars) {
for (int index = 0 ; index < string.length() ; index++) {
if (!allowedChars.contains(string.charAt(index))) {
return false;
}
}
return true;
}
}