Given two strings s and t, determine if they are isomorphic.
Two strings 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.
For example,
Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
Note:
You may assume both s and t have the same length.
Solution in C++: 双向hashtable
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size()!=t.size()) return false;
int idx=0;
map<char, char> mp, rev_mp;
map<char, char>::iterator it;
while(idx<s.size()){
it = mp.find(s[idx]);
if(it!=mp.end()){
char cur = it->second;
if(t[idx]!=cur) return false;
}
else{
it = rev_mp.find(t[idx]);
if(it!=rev_mp.end()) return false;
mp[s[idx]] = t[idx];
rev_mp[t[idx]] = s[idx];
}
idx++;
}
return true;
}
};