Table of contents
Isomorphic Strings
Problem Link:
https://leetcode.com/problems/isomorphic-strings/description/
My approach:
We have to do bi-directional mapping so I used two hashmaps.
Code:
// TIME COMPLEXITY : O(N)
// SPACE COMPLEXITY : O(1) , Hashmaps will never exceed the size of 26
// no matter the size of 's' and 't'.
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size()!=t.size()){
return false;
}
int n = s.size();
unordered_map<char,char> map;
unordered_map<char,char> map1;
for(int i=0;i<n;i++){
// to avoid collision from s to t
if(map.count(t[i])>0 && map[t[i]]!=s[i]){
return false;
}
else{
map[t[i]] = s[i];
}
// to avoid collison from t to s
if(map1.count(s[i])>0 && map1[s[i]]!=t[i]){
return false;
}
else{
map1[s[i]] = t[i];
}
}
return true;
}
};