205. Isomorphic Strings
Hash Table, String ·Problem Statement
link: https://leetcode.com/problems/isomorphic-strings/ https://leetcode.cn/problems/isomorphic-strings/
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.
Example:
Input: s = "egg", t = "add"
Output: true
Input: s = "foo", t = "bar"
Output: false
Input: s = "paper", t = "title"
Output: true
Solution Approach
To determine if two strings are isomorphic, ensure a one-to-one mapping between their characters without any overlaps.
Algorithm
- Length Check: Ensure both strings have equal lengths.
- Map Characters: Utilize a dictionary to relate characters from s to t, and a set to note which characters from t are already mapped.
- Verify Mapping: For each character in s, ensure it maps uniquely to a character in t. If all mappings are consistent, the strings are isomorphic.
Implement
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dic = {}
visited = set()
for i in range(len(s)):
if s[i] in dic:
if dic[s[i]] != t[i]:
return False
else:
if t[i] in visited:
return False
else:
dic[s[i]] = t[i]
visited.add(t[i])
return True