考察的知识点:字符串;
解答方法分析:
- 利用哈希表来建立s中字符与t中字符的映射关系。遍历字符串s和t的每个字符,将字符作为键,对应的字符作为值存入哈希表。
- 在遍历过程中,需要同时检查当前字符是否已经存在于哈希表中,并且保证不同字符不能映射到同一个字符上。如果发现存在冲突,即字符在哈希表中的值与当前的字符不相等,则返回false,表示不是同构的。
- 如果遍历结束后没有发现冲突,即所有字符都满足映射关系,则返回true,表示是同构的。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: string isIsomorphic(string s, string t) { if (s.length() != t.length()) { return "NO"; } unordered_map<char, char> map; for (int i = 0; i < s.length(); i++) { char c1 = s[i]; char c2 = t[i]; if (map.find(c1) != map.end()) { if (map[c1] != c2) { return "NO"; } } else { for (auto it = map.begin(); it != map.end(); it++) { if (it->second == c2) { return "NO"; } } map[c1] = c2; } } return "YES"; } };