Isomorphic Strings [Easy] — Two-Way Character Mapping
Advertisement
Problem Statement
Two strings are isomorphic if characters in s can be replaced to get t, with consistent mapping (no two chars map to same, order preserved).
Input: s="egg", t="add" → true (e→a, g→d)
Input: s="foo", t="bar" → false (o→a and o→r — conflict)
Input: s="paper", t="title" → true
Intuition
Maintain two maps: s→t and t→s. For each pair (sc, tc), check both mappings are consistent.
Solutions
C++
bool isIsomorphic(string s, string t) {
char ms[256]={}, mt[256]={};
for(int i=0;i<s.size();i++){
if(ms[(unsigned char)s[i]]==0&&mt[(unsigned char)t[i]]==0){
ms[(unsigned char)s[i]]=t[i]; mt[(unsigned char)t[i]]=s[i];
} else if(ms[(unsigned char)s[i]]!=t[i]||mt[(unsigned char)t[i]]!=s[i]) return false;
}
return true;
}
Java
public boolean isIsomorphic(String s, String t) {
Map<Character,Character> ms=new HashMap<>(), mt=new HashMap<>();
for(int i=0;i<s.length();i++){
char sc=s.charAt(i), tc=t.charAt(i);
if(ms.containsKey(sc)&&ms.get(sc)!=tc) return false;
if(mt.containsKey(tc)&&mt.get(tc)!=sc) return false;
ms.put(sc,tc); mt.put(tc,sc);
}
return true;
}
Python
def isIsomorphic(s: str, t: str) -> bool:
st, ts = {}, {}
for sc, tc in zip(s, t):
if st.get(sc, tc) != tc or ts.get(tc, sc) != sc:
return False
st[sc] = tc; ts[tc] = sc
return True
JavaScript
var isIsomorphic = function(s, t) {
const st=new Map(), ts=new Map();
for(let i=0;i<s.length;i++){
const sc=s[i], tc=t[i];
if((st.has(sc)&&st.get(sc)!==tc)||(ts.has(tc)&&ts.get(tc)!==sc)) return false;
st.set(sc,tc); ts.set(tc,sc);
}
return true;
};
Complexity
- Time: O(n), Space: O(1) — bounded character set
Advertisement