[LinkedIn]Isomorphic Strings Dictionary substitution

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值