题目:
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中每一个字符之间都是一一对应的关系(即不能出现一对多或多对一的情况)。我们可以维护两张哈希表,一张保存s到t的映射关系,另一张保存t到s的映射关系。如果用C++的unordered_map是可以实现的,但是对于这个问题,由于可以确定输入的字符串中所有可能出现的字符不会超过128种,因此用数组代替unordered_map可以获得性能上的提升。
代码:
class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() == 0) return true; char dic_s[128] = {0}, dic_t[128] = {0}; for (int i = 0; i < s.length(); ++i) { if (dic_s[s[i]] == 0 && dic_t[t[i]] == 0) { dic_s[s[i]] = t[i]; dic_t[t[i]] = s[i]; } else { if (dic_s[s[i]] != t[i] || dic_t[t[i]] != s[i]) { return false; } } } return true; } };