Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to gett.
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.
They key point to store the index of each character. If next round doesn't match, it is false.
bool isIsomorphic(string s, string t) {
if(s.size() != t.size()) return false;
vector<int> sMap(256, 0);
vector<int> tMap(256, 0);
for(int i = 0; i < s.size(); ++i) {
int s_t = (int)s[i];
int t_t = (int)t[i];
if(sMap[s_t] != tMap[t_t]) return false;
if((sMap[s_t] == 0) && (tMap[t_t] == 0)) {
sMap[s_t] = i + 1;
tMap[t_t] = i + 1; // here, it is important here to start from non-zero.
}
}
return true;
}
A more understandable version
bool isIsomorphic(string s, string t) {
if(s.size() == 0 && t.size() == 0) return true;
if(s.size() != t.size()) return false;
char smap[256] = {0};
char tmap[256] = {0};
for(int i = 0; i < s.size(); ++i){
if(smap[s[i]] != tmap[t[i]]){
return false;
}
smap[s[i]] = i + 1;
tmap[t[i]] = i + 1;
}
return true;
}
本文介绍了一种算法,用于判断两个给定的字符串是否为同构字符串。通过存储每个字符的索引来实现这一过程,并确保所有出现的相同字符都被替换为相同的字符,不同字符则映射到不同的字符。
3658

被折叠的 条评论
为什么被折叠?



