题目
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.
For example,
Given “egg”, “add”, return true.
Given “foo”, “bar”, return false.
Given “paper”, “title”, return true.
分析
判断给定的两个字符串是否同构,字符串字面上很容易就能看得出来;
但是怎么用算法来判断呢?
仔细分析:
e <——> a
g <——> d
g <——> d
感觉像离散数学中的双向映射。
在数据结构中可以选择map,选择unordered_map来存储字母映射关系,它的搜索性能为常量。
AC代码
class Solution {
public:
bool isIsomorphic(string s, string t) {
if (s.size() != t.size())
return false;
//求两个字符串的长度
int len = s.size();
//首先验证字符串s—>t的映射
unordered_map<char, char> um;
for (int i = 0; i < len; ++i)
{
auto pos = um.find(s[i]);
if (pos == um.end())
um.insert({ s[i], t[i] });
else{
if ((*pos).second != t[i])
return false;
}//else
}//for
//再验证字符串t—>s的映射
um.clear();
for (int i = 0; i < len; ++i)
{
auto pos = um.find(t[i]);
if (pos == um.end())
um.insert({ t[i], s[i] });
else{
if ((*pos).second != s[i])
return false;
}//else
}//for
return true;
}
};