给定两个字符串 s 和 t,判断它们是否是同构的。
如果 s 中的字符可以被替换最终变成 t ,则两个字符串是同构的。
所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
例如,
给定 "egg", "add", 返回 true.
给定 "foo", "bar", 返回 false.
给定 "paper", "title", 返回 true.
详见:https://leetcode.com/problems/isomorphic-strings/description/
Java实现:
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int[] hash1=new int[256];
int[] hash2=new int[256];
for(int i=0;i<s.length();++i){
if(hash1[s.charAt(i)]!=hash2[t.charAt(i)]){
return false;
}
hash1[s.charAt(i)]=i+1;
hash2[t.charAt(i)]=i+1;
}
return true;
}
}
C++实现:
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;
}
};
参考:https://www.cnblogs.com/grandyang/p/4465779.html