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.
此题目有时间限制,关键是如何优化时间。
我开始的做法是两个for循环,那么时间复杂度就是n的平方,但是它有一个测试用例,两个字符串特别长,于是就出现了“Time Limit Exceeded”。代码如下:
class Solution { public: bool isIsomorphic(string s, string t) {
int len = s.length();
// 时间复杂度n平方,不满足题目要求。
for (size_t i = ; i < len; i++) {
for (size_t j = i + ; j < s.length(); j++) {
if ((s[i] == s[j] && t[i] != t[j]) || (s[i] != s[j] && t[i] == t[j])) {
return false;
}
}
}
return true;
}
};
上面的方法不行,那就必须要减少时间复杂度,最后我想了一个方法:使用一个<char, char>的map映射,for循环两个入参的每一个char,如果发现对应关系改变了,那么就说明两个字符串不是isomorphic的了。时间复杂度为O(n),代码如下:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int len = s.length();
map<char, char> m;
map<char, char> m2;
for (size_t i = ; i < len; i++) {
if (m.find(s[i]) == m.end()) {
m[s[i]] = t[i];
}else if (m[s[i]] != t[i]) {
return false;
}
if (m2.find(t[i]) == m2.end()) {
m2[t[i]] = s[i];
}else if (m2[t[i]] != s[i]) {
return false;
}
}
return true;
}
};