
[문제]
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.
무슨 말인지 몰라서 해설을 조금 찾아봤다..
[입력 조건]
1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character.
[내 풀이]
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# mapping?
s_set = set([s_char for s_char in s])
t_set = set([t_char for t_char in t])
print(s_set)
print(t_set)
if len(s_set) != len(t_set):
return False
else:
str_dict = dict()
for a, b in zip(s,t):
print(a,b)
if a not in str_dict:
str_dict[a] = b
else:
if str_dict[a] != b:
return False
return True
isomorphic의 뜻을 이해한 후에는 바로 풀 수 있었던 문제
주어진 두 문자열 s와 t에 대해 다음과 같은 접근 방식으로 문제를 해결할 수 있습니다.
먼저, 각 문자열에서 중복되지 않는 문자들을 집합으로 추출합니다. 이를 통해 각 문자열에서 사용된 고유한 문자들을 찾을 수 있습니다.
s_set = set([s_char for s_char in s])
t_set = set([t_char for t_char in t])
만약 두 문자열의 고유한 문자 수가 다르다면, 두 문자열은 일대일 대응이 불가능합니다. 따라서 False를 반환합니다.
if len(s_set) != len(t_set):
return False
그렇지 않은 경우, str_dict라는 딕셔너리를 사용하여 s의 각 문자를 t의 각 문자에 매핑합니다. 이때, zip 함수를 사용하여 두 문자열을 동시에 순회합니다.
str_dict = dict()
for a, b in zip(s, t):
if a not in str_dict:
str_dict[a] = b
else:
if str_dict[a] != b:
return False
모든 문자들에 대해 대응이 성공했다면, 두 문자열은 일대일 대응이 가능하므로 True를 반환합니다.
return True
챗지피티의 도움을 받아 작성해보았다.
[출처]
https://leetcode.com/problems/isomorphic-strings/description/