问题描述
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.
思路分析
判断连个字符串是否是同构的,两字符串长度相同。也就是把字母换成编码的话,两个字符串的编码是相同的
s-> 编码相同 <- t
因此我们用两个int的vector来表示两个string的编码,一开始都是置-1,因为0是代表着字母的。然后遍历string,将相应的编码置为第一次出现时的位置,然后在循环过程中对比,编码有没有出现错位,完成同构判断。
代码
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> smap(256, -1);
vector<int> tmap(256, -1);
int n = s.length();
for (int i = 0; i < n; i++){
if (smap[s[i]] != tmap[t[i]])
return false;
smap[s[i]] = i;
tmap[t[i]] = i;
}
return true;
}
};
时间复杂度:
O(n)
空间复杂度:
O(n)
反思
遇到了很大的阻力,没有想明白这道题目的思路。看过博客之后才明白了用数字代替string中字母的方式,然后就可以对字符相应位置的编码是否相同进行判断了。