Home >Backend Development >PHP Tutorial >Count Prefix and Suffix Pairs I
3042. Count Prefix and Suffix Pairs I
Difficulty: Easy
Topics: Array, String, Trie, Rolling Hash, String Matching, Hash Function
You are given a 0-indexed string array words.
Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2:
For example, isPrefixAndSuffix("aba", "ababa") is true because "aba" is a prefix of "ababa" and also a suffix, but isPrefixAndSuffix("abc", "abcd") is false.
Return an integer denoting the number of index pairs (i, j) such that i < j, and isPrefixAndSuffix(words[i], words[j]) is true.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We need to iterate through all index pairs (i, j) where i < j and check whether the string words[i] is both a prefix and a suffix of words[j]. For each pair, we can use PHP's built-in functions substr() to check for prefixes and suffixes.
Let's implement this solution in PHP: 3042. Count Prefix and Suffix Pairs I
Explanation:
countPrefixAndSuffixPairs($words):
- This function loops through all possible index pairs (i, j) such that i < j.
- It calls isPrefixAndSuffix() to check if words[i] is both a prefix and a suffix of words[j].
- If the condition is true, it increments the count.
isPrefixAndSuffix($str1, $str2):
- This helper function checks whether str1 is both a prefix and a suffix of str2.
- It uses substr() to extract the prefix and suffix of str2 and compares them with str1.
- If both conditions are true, it returns true, otherwise, it returns false.
Time Complexity:
For the given input arrays:
This solution should work efficiently within the given constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Prefix A prefix of a string is a substring that starts from the beginning of the string and extends to any point within it. ↩
Suffix A suffix of a string is a substring that begins at any point in the string and extends to its end. ↩
The above is the detailed content of Count Prefix and Suffix Pairs I. For more information, please follow other related articles on the PHP Chinese website!