Today’s problem

https://leetcode.com/problems/count-prefix-and-suffix-pairs-i/description/

Intuition

Do what the question ask!

Approach

Iterate two times and check the suffix and prefix of the string.

Complexity

  • Time complexity: $O(N^2\times L)$, N is the length of the words, and L is the length of the string.

  • Space complexity: $O(1)$

Code

class Solution:
    def countPrefixSuffixPairs(self, words: List[str]) -> int:
        def checkpre(str1, str2):
            if len(str1) > len(str2):
                return False
            return str1 == str2[:len(str1)]
        
        def checksuf(str1, str2):
            if len(str1) > len(str2):
                return False
            return str1 == str2[len(str2) - len(str1):]
        
        ans = 0
        for i in range(len(words)):
            for j in range(i+1, len(words)):
                if checkpre(words[i],words[j]) and checksuf(words[i], words[j]):
                    ans += 1
        
        return ans
class Solution:
    def countPrefixSuffixPairs(self, words: List[str]) -> int:        
        ans = 0
        for i in range(len(words)):
            for j in range(i+1, len(words)):
                if words[j].startswith(words[i]) and words[j].endswith(words[i]):
                    ans += 1
        
        return ans