You are given an array of strings called words. Your task is to count the number of pairs (i, j) (where i < j) such that a string words[i] is both a prefix and a suffix of another string words[j].
str1 is a prefix of str2 if str2 starts with str1.
Example: "ab" is a prefix of "abc", but not of "cab".str1 is a suffix of str2 if str2 ends with str1."bc" is a suffix of "abc", but not of "bca".str1 is both a prefix and suffix of str2
if:
- str2 starts with str1, and
- str2 ends with str1.Input: words = ["a", "aba", "ababa", "aa"]
Output: 4
Explanation:
The valid pairs (i, j) are:
(0, 1) because "a" is both a prefix and suffix of "aba".(0, 2) because "a" is both a prefix and suffix of "ababa".(0, 3) because "a" is both a prefix and suffix of "aa".(1, 2) because "aba" is both a prefix and suffix of "ababa".Input: words = ["pa", "papa", "ma", "mama"]
Output: 2
Explanation:
The valid pairs (i, j) are:
(0, 1) because "pa" is both a prefix and suffix of "papa".(2, 3) because "ma" is both a prefix and suffix of "mama".Input: words = ["abab", "ab"]
Output: 0
Explanation:
No valid pairs exist because none of the strings in words satisfy the condition of being both a prefix and suffix.
1 <= words.length <= 501 <= words[i].length <= 10words[i] contains only lowercase English letters.Return the total number of valid (i, j) pairs where i < j and words[i] is both a prefix and a suffix of words[j].
https://leetcode.com/problems/count-prefix-and-suffix-pairs-i/description/
Loading component...
Loading component...