|
| 1 | +# [Count Prefix and Suffix Pairs I](https://leetcode.com/problems/count-prefix-and-suffix-pairs-i/description/) |
| 2 | + |
| 3 | +You are given a 0-indexed string array words. |
| 4 | + |
| 5 | +Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2: |
| 6 | + |
| 7 | +isPrefixAndSuffix(str1, str2) returns true if str1 is both a prefix and a suffix of str2, and false otherwise. |
| 8 | +For example, isPrefixAndSuffix("aba", "ababa") is true because "aba" is a prefix of "ababa" and also a suffix, but isPrefixAndSuffix("abc", "abcd") is false. |
| 9 | + |
| 10 | +Return an integer denoting the number of index pairs (i, j) such that i < j, and isPrefixAndSuffix(words[i], words[j]) is true. |
| 11 | + |
| 12 | +Example 1: |
| 13 | +``` |
| 14 | +Input: words = ["a","aba","ababa","aa"] |
| 15 | +Output: 4 |
| 16 | +Explanation: In this example, the counted index pairs are: |
| 17 | +i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true. |
| 18 | +i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true. |
| 19 | +i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true. |
| 20 | +i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true. |
| 21 | +Therefore, the answer is 4. |
| 22 | +``` |
| 23 | +Example 2: |
| 24 | +``` |
| 25 | +Input: words = ["pa","papa","ma","mama"] |
| 26 | +Output: 2 |
| 27 | +Explanation: In this example, the counted index pairs are: |
| 28 | +i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true. |
| 29 | +i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true. |
| 30 | +Therefore, the answer is 2. |
| 31 | +``` |
| 32 | +Example 3: |
| 33 | +``` |
| 34 | +Input: words = ["abab","ab"] |
| 35 | +Output: 0 |
| 36 | +Explanation: In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false. |
| 37 | +Therefore, the answer is 0. |
| 38 | +``` |
| 39 | +Solution |
| 40 | +```python |
| 41 | +class Solution: |
| 42 | + def countPrefixSuffixPairs(self, words: List[str]) -> int: |
| 43 | + cnt = 0 |
| 44 | + for a in range(len(words)): |
| 45 | + for b in range(a + 1, len(words)): |
| 46 | + if words[b].startswith(words[a]) and words[b].endswith(words[a]): |
| 47 | + cnt += 1 |
| 48 | + return cnt |
| 49 | +``` |
0 commit comments