问题描述:
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.
For example,
Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
Note:
You may assume both s and t have the same length.
Subscribe to see which companies asked this question
思路:
这道题是判断两个单词是否同构。这里的同构的意思是,对于例子egg和add,若存在一个映射,e->a,g->d,单词egg和add同构。注意,不可以多个字符映射到同一个字符中去,比如aa和ab。因此要有两个hash表来记录。由于是字符,不会超过256个,因此可以用数组来记录这种映射。
代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.length() != t.length()) return false;
char charmap1[256];
char charmap2[256];
memset(charmap1,0,sizeof(char) * 256);
memset(charmap2,0,sizeof(char) * 256);
for(int i = 0; i < s.length();++i){
if(charmap1[s[i]] == 0){
charmap1[s[i]] = t[i] ;
}
else if(charmap1[s[i]] != t[i]){
return false;
}
if(charmap2[t[i]] == 0){
charmap2[t[i]] = s[i] ;
}
else if(charmap2[t[i]] != s[i]){
return false;
}
}
return true;
}
};