Isomorphic Strings leetcode
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.
题目很简单,也很容易想到方法,就是记录遍历s的每一个字母,并且记录s[i]到t[i]的映射,当发现与已有的映射不同时,说明无法同构,直接return false。但是这样只能保证从s到t的映射,不能保证从t到s的映射,所以交换s与t的位置再重来一遍上述的遍历就OK了。
举一个例子为什么需要两次映射
如果是 "ega"和"add" 那么g和a都会映射到d,如何要保证一一对应,需要双向映射关系
bool check(string s, string t) { 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()) map[c1] = c2; else if (map[c1] != c2) return false; } return true; } bool isIsomorphic(string s, string t) { return check(s, t) && check(t, s); }