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
分析:
问两个字符串是否为同构字符串。同构字符串即两个字符串对应为构成相互映射,且同一个字符不能映射两个不同的字符,但是可以映射其本身。由于256个字符有Ascii码,所以定义2个长度为256初始值全为0的数组m1, m2。遍历原字符串,分别从源字符串和目标字符串取出一个字符,然后分别在两个数组中查找其值,若不相等,则返回false,若相等,将其值更新为i+1。
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256] = {0};
int m2[256] = {0};
int len = s.size();
for(int i=0; i<len; i++)
{
if(m1[s[i]] != m2[t[i]])
return false;
else
{
m1[s[i]] = i+1;
m2[t[i]] = i+1;
}
}
return true;
}
};