3042. Count Prefix and Suffix Pairs I #1102
-
Topics: You are given a 0-indexed string array words. Let's define a boolean function
For example, Return an integer denoting the number of index pairs Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to iterate through all index pairs Let's implement this solution in PHP: 3042. Count Prefix and Suffix Pairs I <?php
/**
* @param String[] $words
* @return Integer
*/
function countPrefixAndSuffixPairs($words) {
// Initialize a counter to keep track of valid index pairs
$count = 0;
// Loop through all index pairs (i, j) where i < j
for ($i = 0; $i < count($words); $i++) {
for ($j = $i + 1; $j < count($words); $j++) {
// Check if words[i] is both a prefix and a suffix of words[j]
if (isPrefixAndSuffix($words[$i], $words[$j])) {
$count++;
}
}
}
return $count;
}
/**
* Function to check if str1 is both a prefix and a suffix of str2
*
* @param $str1
* @param $str2
* @return bool
*/
function isPrefixAndSuffix($str1, $str2) {
// Check if str1 is a prefix and a suffix of str2
return (substr($str2, 0, strlen($str1)) === $str1 && substr($str2, -strlen($str1)) === $str1);
}
// Example Test Cases
$words1 = ["a", "aba", "ababa", "aa"];
$words2 = ["pa", "papa", "ma", "mama"];
$words3 = ["abab", "ab"];
echo countPrefixAndSuffixPairs($words1) . "\n"; // Output: 4
echo countPrefixAndSuffixPairs($words2) . "\n"; // Output: 2
echo countPrefixAndSuffixPairs($words3) . "\n"; // Output: 0
?> Explanation:
Time Complexity:
Example Output:For the given input arrays:
This solution should work efficiently within the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to iterate through all index pairs
(i, j)
wherei < j
and check whether the stringwords[i]
is both a prefix and a suffix ofwords[j]
. For each pair, we can use PHP's built-in functionssubstr()
to check for prefixes and suffixes.Let's implement this solution in PHP: 3042. Count Prefix and Suffix Pairs I