1684. Count the Number of Consistent Strings #530
-
Topics: You are given a string Return the number of consistent strings in the array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The idea is to check if each word in the Plan
Let's implement this solution in PHP: 1684. Count the Number of Consistent Strings <?php
/**
* @param String $allowed
* @param String[] $words
* @return Integer
*/
function countConsistentStrings($allowed, $words) {
// Step 1: Create a set (array) for allowed characters
$allowedSet = [];
for ($i = 0; $i < strlen($allowed); $i++) {
$allowedSet[$allowed[$i]] = true;
}
// Step 2: Initialize counter for consistent strings
$consistentCount = 0;
// Step 3: Check each word in words array
foreach ($words as $word) {
$isConsistent = true;
for ($j = 0; $j < strlen($word); $j++) {
// If the character is not in the allowed set, mark the word as inconsistent
if (!isset($allowedSet[$word[$j]])) {
$isConsistent = false;
break;
}
}
// Step 4: If the word is consistent, increment the counter
if ($isConsistent) {
$consistentCount++;
}
}
// Step 5: Return the count of consistent strings
return $consistentCount;
}
// Example usage:
// Example 1:
$allowed = "ab";
$words = ["ad", "bd", "aaab", "baa", "badab"];
echo countConsistentStrings($allowed, $words); // Output: 2
// Example 2:
$allowed = "abc";
$words = ["a","b","c","ab","ac","bc","abc"];
echo countConsistentStrings($allowed, $words); // Output: 7
// Example 3:
$allowed = "cad";
$words = ["cc","acd","b","ba","bac","bad","ac","d"];
echo countConsistentStrings($allowed, $words); // Output: 4
?> Explanation:
Time Complexity:
Example Walkthrough:For the input: $allowed = "ab";
$words = ["ad", "bd", "aaab", "baa", "badab"];
Thus, the function returns Constraints Handling:
|
Beta Was this translation helpful? Give feedback.
The idea is to check if each word in the
words
array is consistent with the characters in theallowed
string. A word is consistent if all its characters are present in theallowed
string.Plan
Allowed Characters Set:
allowed
string into a set of characters to efficiently check if each character in the word exists in the set.Word Consistency Check:
words
array, check if all its characters exist in theallowed
set.Count Consistent Words:
Return the Count:
Let's implement this solution in…