同构string
leetcode新题,另外似乎是L家面经题
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中两个char map到t中相同char,所以同时还需要check当前t[i]是否已经对应其他char了,这样就需要两个map来保存map pair的关系
例如 ab, aa return false
//use hashmap to record map of (s, t) public boolean isIsomorphic(String s, String t) { if(s == null && t == null) { return true; } if(s.length() != t.length()) { return false; } HashMap<Character, Character> map1 = new HashMap<Character, Character>();//s[i], t[i] HashMap<Character, Character> map2 = new HashMap<Character, Character>();//t[i], s[i] for(int i = 0; i < s.length(); i++){ char schar = s.charAt(i); char tchar = t.charAt(i); if(map1.containsKey(schar) && map1.get(schar) != tchar){ return false; // map to wrong char } //check no two map to same char in t if(map2.containsKey(tchar) && map2.get(tchar) != schar ){ return false; } map1.put(schar, tchar); map2.put(tchar, schar); } return true; }
然后在此基础上 拓展 counting 同构words数目
given: a list of N words, each up to K characters, return: number of pairs of isomorphic words
isomorphic pair: can permute alphabet of one word to alphabet of the other word
can remap alphabet of one word to alphabet of the other word
can replace all occurrences of one letter with a different letter to get the other word, and no two letters can map to the same letter
example:
> xzrxr
> qwoqo
> ktvkv
> xxxyy
> nnnhh
return 4
基础想法brute force,双重循环看每一个word和其他word是否是同构词, 调用上面函数 O(n^2 * K)
Better solution:替换
> xzrxr -> abcac
> qwoqo -> abcac
> ktvkv -> abcac
> xxxyy -> aaabb
> nnnhh -> aaabb