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.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
分析一
题目的意思是:判断两个字符串是否是同构的。
- 用两个hash表来建立两字符串字符的映射,如果出现一对多的映射,说明就不是同构的。
代码一
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char,char> res,st;
for(int i=0;i<s.length();i++){
if(res.count(s[i])||st.count(t[i])){
if(res[s[i]]!=t[i]||st[t[i]]!=s[i]){
return false;
}
}else{
res[s[i]]=t[i];
st[t[i]]=s[i];
}
}
return true;
}
};
分析二
- 两个哈希表分别来记录原字符串和目标字符串中字符出现情况,由于ASCII码只有256个字符,所以我们可以用一个256大小的数组来代替哈希表,并初始化为0;
- 我们遍历原字符串,分别从源字符串和目标字符串取出一个字符,然后分别在两个哈希表中查找其值,若不相等,则返回false,若相等,将其值更新为i + 1,因为默认的值是0,所以我们更新值为i + 1,这样当 i=0 时,则映射为1,如果不加1的话,那么就无法区分是否更新了。
代码二
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256] = {0}, m2[256] = {0}, n = s.size();
for (int i = 0; i < n; ++i) {
if (m1[s[i]] != m2[t[i]]) return false;
m1[s[i]] = i + 1;
m2[t[i]] = i + 1;
}
return true;
}
};
Python实现
用两个字典进行模拟即可:
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
st = dict()
ts = dict()
for s1,t1 in zip(s,t):
if s1 not in st:
st[s1]=t1
if t1 not in ts:
ts[t1]=s1
if st[s1]!=t1 or ts[t1]!=s1:
return False
return True