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.
思路:
刚开始我的做法是用无序哈希表,对应表中元素看看是不是一样,遍历一遍。但是这样做要29ms,后来看了别人的做法。他的思路是,对字符串中每个字符都编好号在一个int数组中,在遍历到后面字符时,可以通过找到int数组中后面字符相应的前面字符的序号。假如要比较的两个字符的前面的字符都相等,那么就是正确的,要是不相等,就不正确
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char,char> maps1,maps2;
for(int i=0;i<s.size();i++)
{
if(maps1.find(s[i])==maps1.end())
{
maps1.insert({s[i], t[i]});
}
else
{
if(maps1[s[i]]!=t[i])
return false;
}
}
for(int i=0;i<t.size();i++)
{
if(maps2.find(t[i])==maps2.end())
{
maps2.insert({ t[i], s[i] });
}
else
{
if(maps2[t[i]]!=s[i])
return false;
}
}
return true;
}
};
他人做法:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256]={0},m2[256]={0};
for(int i=0;i<s.size();i++)
{
if(m1[s[i]]!=m2[t[i]])
return false;
m1[s[i]]=i+1;
m2[t[i]]=i+1;
}
return true;
}
};