
Problem Description:
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.
题目大意:
给定两个字符串,判断它们是否是相似的。
Solutions:
用两个哈希表判断两个字符之间是否是一一对应的即可。
Code in C++:
class Solution {
public:
bool isIsomorphic(string s, string t) {
std::map<char,char> m;
std::map<char,char> mr;
std::map<char,char>::iterator it;
std::map<char,char>::iterator itr;
for(int i = 0; i < s.length(); i++)
{
it = m.find(s[i]);
itr = mr.find(t[i]);
if(it!=m.end()||itr!=mr.end())
{
if(m[s[i]]!=t[i]||mr[t[i]]!=s[i]) return false;
}else{
m[s[i]]=t[i];
mr[t[i]]=s[i];
}
}
return true;
}
};




近期评论