SeangG
def _(): _()
SeangG
전체 방문자
오늘
어제
  • 분류 전체보기 (37)
    • Programming Language (0)
      • Python (0)
      • Web (0)
    • Algorithm (34)
    • Art (0)
      • 3D Modeling (0)
      • Pixel (0)
      • Picture (0)
    • Game (0)
    • Project (3)
      • Problems (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Python
  • BFS
  • LeedCode
  • 매핑 테이블
  • leetcode
  • next.js
  • Queue
  • WSL
  • Leecode
  • github oauth
  • graph
  • string
  • 로마 숫자
  • spring boot
  • dfs
  • Daily Question
  • react.js
  • Tree
  • 문자열
  • Fast Refresh

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
SeangG

def _(): _()

Algorithm

[LeetCode] 205. Isomorphic Strings (Daily Question)

2024. 4. 2. 11:22

문제


Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

 

주어진 두 문자열 s, t가 같은 구조인지 판별하는 문제이다.

 

예를 들면, egg와 add는 구조상(이런 구조:🐥🐧🐧)으로 볼 때 같다고 할 수 있다.

다른 예로, abbd와 bccb는 다르다고 할 수 있다.


 

풀이


아이디어

치환암호처럼 s의 각 문자를 t에 대해 매핑한다.

 

코드

# s의 각 문자를 t에 대해 매핑
class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        # 매핑 테이블
        table = {}

        # 이미 매핑된 문자를 저장할 set (중복매핑 방지)
        used = set([])

        for sc, tc in zip(s, t):
            # 매핑 테이블과 일치하지 않은 경우
            if sc in table and table[sc] != tc:
                return False
            
            # 아직 매핑되지 않은 경우
            elif sc not in table:
                # 중복 매핑되는 경우
                if tc in used: 
                    return False
                table[sc] = tc
                used.add(tc)
            
            # else 매핑된 값이 일치한 경우 continue

        return True

중복 매핑은 같은 대상으로 매핑될 때를 말한다.

예를 들면, s=ac와 t=bb가 주어졌을 때 s의 a, c 모두 b로 매핑된다. (a->b, c->b)

 


 

후기


난이도

어떤 방식으로 풀 지 생각해내기만 한다면 구현하기에는 쉬운 문제였다.

예외상황도 딱히 없었기에 까다롭다는 느낌은 없었다.

 

다른 풀이

양쪽 문자열 모두 변환시켜 비교하는 방법이 있다.

ABCA -> 0120,   GOSG -> 0120

매핑테이블이 두 개가 필요하지만, 중복매핑을 고려할 필요는 없어진다.

'Algorithm' 카테고리의 다른 글

[LeetCode] 1544. Make The String Great (Daily Question)  (0) 2024.04.05
[LeetCode] 1111. Maximum Nesting Depth of Two Valid Parentheses Strings  (0) 2024.04.04
[LeetCode] 1614. Maximum Nesting Depth of the Parentheses (Daily Question)  (0) 2024.04.04
[LeetCode] 79. Word Search (Daily Question)  (0) 2024.04.03
[LeetCode] 12. Integer to Roman  (0) 2024.04.02
    'Algorithm' 카테고리의 다른 글
    • [LeetCode] 1111. Maximum Nesting Depth of Two Valid Parentheses Strings
    • [LeetCode] 1614. Maximum Nesting Depth of the Parentheses (Daily Question)
    • [LeetCode] 79. Word Search (Daily Question)
    • [LeetCode] 12. Integer to Roman
    SeangG
    SeangG

    티스토리툴바