반응형
https://leetcode.com/problems/count-prefix-and-suffix-pairs-i
전수조사 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
단어의 길이 length, 정답 ans를 선언 후 적절히 저장합니다.
📔 풀이과정
이중 for loop를 수행하며 서로 다른 두 단어를 뽑아 접두어와 접미사라면 해당 쌍을 찾았으므로 ans를 1씩 추가합니다.startswith, endswith를 사용하면 간단한 구현으로 알 수 있습니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 Python3
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
length = len(words)
ans = 0
def isPrefixAndSuffix(word1: str, word2: str) -> bool:
return word2.startswith(word1) and word2.endswith(word1)
for i in range(length):
for j in range(i+1, length):
if isPrefixAndSuffix(words[i], words[j]):
ans += 1
return ans
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.