题目要求:
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.
Note:
You may assume both s and t have the same length.
这题难度不大。
第一个程序(28ms):
bool isIsomorphic(string s, string t) {
unordered_map<char, char> hashMap;
int sz = s.size();
for(int i = ; i < sz; i++)
{
if(hashMap.find(s[i]) != hashMap.end())
{
if(hashMap[s[i]] != t[i])
return false;
}
else
{
unordered_map<char, char>::iterator itr = hashMap.begin();
for(; itr != hashMap.end(); itr++)
if(itr->second == t[i])
return false; hashMap[s[i]] = t[i];
} } return true;
}
第二个程序(24ms):
bool isIsomorphic(string s, string t) {
unordered_map<char, char> hashMap;
unordered_map<char, char> rHashMap;
int sz = s.size();
for(int i = ; i < sz; i++)
{
if(hashMap.find(s[i]) != hashMap.end())
{
if(hashMap[s[i]] != t[i])
return false;
}
else
{
if(rHashMap.find(t[i]) != rHashMap.end())
return false; hashMap[s[i]] = t[i];
rHashMap[t[i]] = s[i];
}
} return true;
}
看了网上别人的做法(少掉了哈希表查找的时间损耗),只需8ms:
bool isIsomorphic(string s, string t) {
char map_s[] = { };
char map_t[] = { };
int len = s.size();
for (int i = ; i < len; ++i)
{
if (map_s[s[i]]!=map_t[t[i]]) return false;
map_s[s[i]] = i+;
map_t[t[i]] = i+;
} return true;
}