https://leetcode.com/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 1: Input: s = “egg”, t = “add” Output: true Example 2: Input: s = “foo”, t = “bar” Output: false Example 3: Input: s = “paper”, t = “title” Output: true
Constraints:
1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character.
- code
class Solution {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character, Character> m = new HashMap<>();
Set<Character> v = new HashSet<>();//mapped values
for (int i = 0; i < s.length(); i++){
if (!m.containsKey(s.charAt(i))){
if (v.contains(t.charAt(i))) return false;
m.put(s.charAt(i), t.charAt(i));
v.add(t.charAt(i));
}else{
if (m.get(s.charAt(i)) != t.charAt(i)) return false;
}
}
return true;
}
}
- code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
- code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
match = {}
for i in range(len(s)):
if s[i] not in match:
if t[i] in match.values():
return False
match[s[i]] = t[i]
else:
if match[s[i]] != t[i]:
return False
return True
- code
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
d= {}
if len(set(s)) != len(set(t)): return False
for i in range(len(s)):
if s[i] in d and d[s[i]] != t[i]:
return False
else:
d[s[i]] = t[i]
return True