-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfConsistentStrings.java
More file actions
40 lines (33 loc) · 1.26 KB
/
NumberOfConsistentStrings.java
File metadata and controls
40 lines (33 loc) · 1.26 KB
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
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
// Array to keep track of allowed characters
boolean[] isAllowed = new boolean[26];
// Populate the isAllowed array with characters from the 'allowed' string
for (char c : allowed.toCharArray()) {
isAllowed[c - 'a'] = true;
}
// Initialize count for consistent strings
int count = 0;
// Iterate through each word in the array 'words'
for (String word : words) {
// If the word is consistent, increment the count
if (isConsistent(word, isAllowed)) {
count++;
}
}
// Return the total count of consistent strings
return count;
}
// Helper method to check if a word is consistent
private boolean isConsistent(String word, boolean[] isAllowed) {
// Iterate through each character in the word
for (int i = 0; i < word.length(); i++) {
// If the character is not in the allowed list, return false
if (!isAllowed[word.charAt(i) - 'a']) {
return false;
}
}
// Return true if all characters of the word are allowed
return true;
}
}