Problem
Given two strings s
and t
, determine if they are isomorphic.
Two strings s
and t
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.
Solution
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool isomorphic_strings::isIsomorphic(string s, string t) {
map<char, char> m;
map<char, char> p;
for (int i = 0; i < s.length(); ++i) {
char ss = s.at(i);
char tt = t.at(i);
map<char, char>::iterator iter = m.find(ss);
if (iter != m.end()) {// 有映射过
if (iter->second != tt) {
return false;
}
} else {// 没有映射过
// 判断能不能映射为
iter = p.find(tt);
if (iter != p.end()) {// 已经被映射过
if (iter->second != ss) {
return false;
}
} else {
m[ss] = tt;
p[tt] = ss;
}
}
}
return true;
}
References
https://leetcode.com/problems/isomorphic-strings/?envType=study-plan&id=level-1