Isomorphic Strings
Total Accepted: 39963 Total Submissions: 145129 Difficulty: Easy
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:
bool isIsomorphic(string s, string t) {
map<char,char> ma;
map<char,char>::iterator it;
int lenS=s.length();
for(int i=0;i<lenS;i++){
if((it=ma.find(t[i]))==ma.end()){
ma[t[i]]=s[i];
}else{
if(it->second!=s[i]){
return false;
}
}
}
ma.clear();
for(int i=0;i<lenS;i++){
if((it=ma.find(s[i]))==ma.end()){
ma[s[i]]=t[i];
}else{
if(it->second!=t[i]){
return false;
}
}
}
return true;
}
};