0%

[Leetcode]205. Isomorphic Strings(C++)

题目描述

题目链接:205. Isomorphic Strings

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.

例子

例子 1

Input: s = “egg”, t = “add”
Output: true

例子 2

Input: s = “foo”, t = “bar”
Output: false

例子 3

Input: s = “paper”, t = “title”
Output: true

Note

You may assume both s and t have the same length.

解题思路

注意到这里题目中考虑到字母之间的对应关系,很容易想到用哈希表来建立对应关系,这里要注意一点:对应关系是双向的,即两边字符之间都是一一对应的,不存在从哪个字符串可以多对一。因此需要用两个哈希表分别建立对应关系。另外题目注明了字符串长度一致,否则还要对字符串长度进行判断,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <unordered_map>
#include <string>

class Solution {
public:
bool isIsomorphic(std::string s, std::string t) {
std::unordered_map<char, char> dist;
std::unordered_map<char, char> rev_dist;
for (int i = 0; i < s.length(); i++) {
if (dist.find(s[i]) == dist.end()) {
dist[s[i]] = t[i];
} else if (dist[s[i]] != t[i]) {
return false;
}
if (rev_dist.find(t[i]) == rev_dist.end()) {
rev_dist[t[i]] = s[i];
} else if (rev_dist[t[i]] != s[i]) {
return false;
}
}
return true;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1) 字符数量为常数