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.
题目要求:判断两个字符串的模式相同,及用一个字符串中的字符替换相同位置的第二个字符串中的字符,得到的字符串与第一个字符串相同。
Python3
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
hashmap = {}
for i in range(len(s)):
if s[i] not in hashmap:
hashmap[s[i]] = t[i]
elif hashmap[s[i]] != t[i]:
return False
val = [hashmap[i] for i in hashmap]
return len(val) == len(set(val))
C++(AC里看到的,比较巧妙)
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> v1(256, -1), v2(256, -1);
for(int i=0; i<s.size(); ++i)
{
if(v1[s[i]] != v2[t[i]])
return false;
v1[s[i]] = v2[t[i]] = i;
}
return true;
}
};