问题描述:
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.
Example 1:
Input: s = "egg",
t = "add"
Output: true
Example 2:
Input: s = "foo",
t = "bar"
Output: false
Example 3:
Input: s = "paper",
t = "title"
Output: true
Note:
You may assume both s and t have the same length.
简述:
给定相同长度字符串s,t,判断字符串s是否可以通过字符替换成t(不能将两个不同字符替换成同一个字符)。
解题思路:
通过map保存字符的替换情况,因为不能将两个不同字符替换成同一字符,即字符替换是一对一映射。使用两个map维持这种一对一映射关系。使用m1,m2分别保存串s,t的替换关系,遍历串s,将s[i]替换为t[i],如当前替换关系存在冲突,返回false。若能顺利遍历完两个串,返回true。
bool isIsomorphic(string s, string t) {
map<char, char> m1, m2;
for(int i=0; i<s.length(); ++i) {
if((m1.find(s[i]) == m1.end()) && (m2.find(t[i])==m2.end())) {
m1[s[i]] = t[i];
m2[t[i]] = s[i];
} else if((m1.find(s[i]) != m1.end()) && (m2.find(t[i]) != m2.end())){
if((m1[s[i]] != t[i]) || (m2[t[i]] != s[i])) return false;
} else {
return false;
}
}
return true;
}