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.
class Solution {
public:
void feature(string &s, map<char, vector<int> >& m){
for(int i=0;i<s.size();i++){
if(m.count(s[i]) == 0){
vector<int> v = vector<int>();
v.push_back(i);
m[s[i]] = v;
}else{
m[s[i]].push_back(i);
}
}
}
bool compare(map<char, vector<int> >m, vector<int> diff){
for (std::map<char,vector<int> >::iterator it=m.begin(); it!=m.end(); ++it){
vector<int> &v = it->second;
if(v.size() > 0){
for(int i=1;i<v.size();i++){
if(diff[v[0]] != diff[v[i]])
return false;
}
}
}
return true;
}
bool isIsomorphic(string s, string t) {
// You may assume both s and t have the same length.
if(s.size() == 0) return true;
map<char, vector<int> >ms = map<char, vector<int> >();
map<char, vector<int> >mt = map<char, vector<int> >();
vector<int> diff = vector<int>();
feature(s, ms);
feature(t, mt);
for(int i=0;i<s.size();i++){
diff.push_back(s[i] - t[i]);
}
return compare(ms, diff) && compare(mt, diff);
}
};