[LinkedIn]Isomorphic Strings Dictionary substitution

来源:互联网 发布:mac版围棋对弈软件 编辑:程序博客网 时间:2024/06/16 18:59

From Here
Given two (dictionary) words as Strings, determine if they are isomorphic.

Two words are called isomorphic if the letters in one word can be remapped to get the second word. Remapping a letter means replacing all occurrences of it with another letter while the ordering of the letters remains unchanged. No two letters may map to the same letter, but a letter may map to itself.

Wrong Solution:
map char to char, then check in the hashmap. However, this will not work!
since no two letters may map to the same letter. This will damage the rule

Best solution:
HashMap (char, firstSeenIndice) for each string. The encoding of firstSeenIndices should match.
E.g. Foo and app both encode to 011
Abcd and hole both encode to 0123

public boolean isomorphic(String s, String t) {    if (s.length() != t.length()) {        return false;    }    return (sequence(s).equals(sequence(t)));}private String sequence(String s) {    HashMap<Character, Integer> map = new HashMap<Character, Integer>();    StringBuilder sb = new StringBuilder();    for (int i = 0; i < s.length(); i++) {        if (map.containsKey(s.charAt(i))) {            sb.append(map.get(s.charAt(i)));        } else {            map.put(s.charAt(i), i);        }    }    return sb.toString();}
0 0
原创粉丝点击