Isomorphic Strings
Isomorphic Strings
Two strings are isomorphic when characters in string S can replace characters in string T to make them identical. The mapping rule: each character maps to exactly one other character. Different source characters cannot map to the same target character.
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<char> m(257, '#');
vector<bool> count(257, false);
// Build the mapping
for(int i=0;i<s.size();++i) {
int idx = s[i];
if(m[idx] == '#') {
m[idx] = t[i];
} else if (m[idx]!=t[i]) {
return false;
}
}
// Check if any target character has multiple sources
for(int i=0;i<m.size();++i) {
if (m[i] == '#') continue;
int idx = m[i];
if (count[idx] == false) {
count[idx] = true;
} else {
return false;
}
}
return true;
}
};#string