建立s到t以及t到s的哈希映射
遍历两个字符串,当双方都不存在某字符的映射关系时,加入映射;
如果某字符的映射关系在两个映射表中产生冲突,返回false
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param t string字符串
* @return bool布尔型
*/
bool isIsomorphic(string s, string t) {
int n = s.size();
if (n != t.size()) {
return false;
}
unordered_map<char, char> stot; // s到t的映射
unordered_map<char, char> ttos; // t到s的映射
for (int i = 0; i < n; i++) {
if (stot.count(s[i]) == 0 && ttos.count(t[i]) == 0) {
stot[s[i]] = t[i];
ttos[t[i]] = s[i];
} else if (stot[s[i]] != t[i] || ttos[t[i]] != s[i]) {
return false;
}
}
return true;
}
};
时间复杂度:O(n),n为字符串长度,需要遍历一次字符串
空间复杂度:O(n),存储两张哈希表

京公网安备 11010502036488号