래원

[LeetCode] 3042. Count Prefix and Suffix Pairs I (Python) 본문

알고리즘/LeetCode

[LeetCode] 3042. Count Prefix and Suffix Pairs I (Python)

Laewon Jeong 2025. 1. 8. 14:47

 

난이도: Easy

 

문제 설명


You are given a 0-indexed string array words.

Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2:

  • isPrefixAndSuffix(str1, str2) returns true if str1 is both a  prefix and a suffix of str2, and false otherwise.

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:

Input: words = ["a","aba","ababa","aa"]
Output: 4
Explanation: In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.

Example 2:

Input: words = ["pa","papa","ma","mama"]
Output: 2
Explanation: In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2.

Example 3:

Input: words = ["abab","ab"]
Output: 0
Explanation:In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.

 

제한사항


  • 1 <= words.length <= 50
  • 1 <= words[i].length <= 10
  • words[i] consists only of lowercase English letters.

 

Solution(솔루션)

class Solution:
    def countPrefixSuffixPairs(self, words: List[str]) -> int:
        n = len(words)
        answer = 0

        for i in range(n):
            for j in range(i+1, n):
                if words[j].find(words[i]) == 0 and words[j].rfind(words[i]) == len(words[j])-len(words[i]):
                    answer += 1
        
        return answer

 

이 문제 역시 제한사항을 보고 그냥 Brute Force 방식으로 해결했다.

 

find와 rfind 함수를 사용해서 words[j]의 접미사와 접두사가 words[i]로 이루어져 있는지 확인하고 맞다면 answer +1을 하였다.

 

모든 단어를 확인하면 마지막에 answer를 return 하여 정답을 맞출 수 있었다.


문제: 3042. Count Prefix and Suffix Pairs I

깃허브: github

 

algorithm_practice/LeetCode/3309-count-prefix-and-suffix-pairs-i at main · laewonJeong/algorithm_practice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithm_practice development by creating an account on GitHub.

github.com