一、问题描述
Given two strings
Two strings are isomorphic if the characters in
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.
Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
You may assume both
二、解题报告
所谓的“同构”,就是字符串 s 中的字符可以一对一的映射到字符串 t 中的字符。不能一对多,也不能多对一。
这里,我的解法是维护两个
// s 和 t 具有相同的长度
bool isIsomorphic(string s, string t) {
map<char, char> m1;
map<char, char> m2;
bool flag = true;
for(int i=0; i<s.size(); ++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])
{
flag = false;
break;
}
}
else
{
flag = false;
break;
}
}
return flag;
}
LeetCode答案源代码:https://github.com/SongLee24/LeetCode