给定两个字符串 s 和 t,判断它们是否是同构的。
如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。
所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
示例1:
输入: s = "egg", t = "add"
输出: true
示例2:
输入: s = "foo", t = "bar"
输出: false
示例3:
输入: s = "paper", t = "title"
输出: true
说明:
你可以假设 s 和 t 具有相同的长度。
这个题开始的思路是设置两个哈希表,存储两个字符串每个位置字符对应的值,第一位就是1,第二位就是2,以此类推,然后如果表内已有值就不添加直接加值,最后形成两个数字组成的字符串,如果这两个字符串相等则同构。
C++源代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char, string> m,n;
string numS="", numT="";
int len = s.length();
for(int i=0;i<len;i++)
{
if(m.find(s[i])==m.end())
{
m[s[i]] = to_string(i+1);
numS += m[s[i]];
}
else numS += m[s[i]];
if(n.find(t[i])==n.end())
{
n[t[i]] = to_string(i+1);
numT += n[t[i]];
}
else numT += n[t[i]];
}
return numS == numT;
}
};
还有一种写起来更简单的方法,字符一定在ascii码表中,定义一个256的数组,所以两个字符串一起遍历的话,遇到字符就将其ascii值对应的位置置为当前字符位置值,这样也起到了两个字符对应同一值的作用,然后如果查找到某一位置的两个字符其ascii值对应的数组中的值不同,说明不同构。
python3源代码:
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
m = [0]*256
n = [0]*256
for i in range(len(s)):
if m[ord(s[i])]!=n[ord(t[i])]:
return False
m[ord(s[i])] = i+1
n[ord(t[i])] = i+1
return True