소프트웨어에 대한 모든 것

LeetCode 풀기 - 890. Find and Replace Pattern 본문

알고리즘/LeetCode

LeetCode 풀기 - 890. Find and Replace Pattern

앤테바 2021. 11. 9. 07:51
반응형

890. Find and Replace Pattern

https://leetcode.com/problems/find-and-replace-pattern/

 

Find and Replace Pattern - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1)

class Solution:
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        matched = []
        unique_char_count = len(set(list(pattern)))

        for word in words:
            if len(set(list(word))) != unique_char_count:
                continue

            # char 매핑
            mapping = {}

            # 매핑에 의해서 생성된 단어
            created_word = ''
            for i, c in enumerate(word):
                if c in mapping:
                    # 이미 매핑되어 있다면 사용
                    created_word += mapping[c]
                else:
                    # 매핑되어 있지않으면 새로운 매핑을 추가
                    mapping[c] = pattern[i]
                    created_word += pattern[i]

            # 매핑에 의해성 생성된 단어가 패턴가 동일한가?
            if created_word == pattern:
                matched.append(word)

        return matched

솔루션2)

dict의 setdefault() 함수를 이용한다.

매핑 테이블을 만들고 숫자로 변환된 값이 동일한지 체크한다.

 

예시)

pattern : "abb" -> 011

word1 : "abc" -> 012 (not matched)

word2 : "aba" -> 010 (not matched)

word3 : "mee" -> 011 (matched)

class Solution:
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        def mapping(word):
            m = {}
            return [m.setdefault(c, len(m)) for c in word]
        
        pattern_mapping = mapping(pattern)
        return [word for word in words if mapping(word) == pattern_mapping]

 

반응형
Comments