개발/Leetcode

Leetcode 2744. Find Maximum Number of String Pairs

지산동고라니 2023. 7. 1. 09:59

https://leetcode.com/problems/find-maximum-number-of-string-pairs/description/

 

Find Maximum Number of String Pairs - LeetCode

Can you solve this real interview question? Find Maximum Number of String Pairs - You are given a 0-indexed array words consisting of distinct strings. The string words[i] can be paired with the string words[j] if: * The string words[i] is equal to the rev

leetcode.com

문제

고유한 문자열 값을 가지며 0-indexed인 배열 words가 주어진다.

words[i]와 words[j]는 아래와 같은 조건이되면 짝이 될 수 있다.

  • words[i] 문자열을 거꾸로 한 값이 words[j]와 같다
  • 0 <= i < j < words.length

주어진 배열 words에서 최대의 짝의 갯수를 구하여 반환하라.

 

코드

from collections import defaultdict

class Solution:
    def maximumNumberOfStringPairs(self, words: List[str]) -> int:
        m = defaultdict(int)
        for word in words:
            m[word] += 1
            if word != word[::-1]:
                m[word[::-1]] +=1
        # print(m)
        return len(list(filter(lambda x: x == 2, m.values()))) // 2