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.

 

 

用两个map记录一下对应的字母,由于必须是一一对应,所以用了两个map。

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> map = new HashMap();
        Map<Character, Character> map2 = new HashMap();
        for (int i = 0; i < s.length(); i++){
            char ch = t.charAt(i);
            char sh = s.charAt(i);
            if (map.containsKey(sh)){
                if (ch != map.get(sh)){
                    return false;
                }
            } else {
                
                if (map2.containsKey(ch)){
                    return false;
                }
                map.put(sh, ch);
                map2.put(ch, sh);
            }
        }
        return true;
    }
}

1、用一个map也可以,因为可以用containsValue()这个方法。

2、也可以不用map,用数组就可以。注意的是数组大小,最好开两个256.

 

3、也可以直接开一个数组,更简单。

public class Solution {
    public boolean isIsomorphic(String s1, String s2) {
        int[] m = new int[512];
        for (int i = 0; i < s1.length(); i++) {
            if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
            m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
        }
        return true;
    }
}