Isomorphic Strings

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.

Example

Given s = "egg", t = "add", return true.

e-> a, g-> d, g -> d true

Given s = "foo", t = "bar", return false.

f-> b, o -> a, o-> r 不能一个字母映射两个

Given s = "paper", t = "title", return true.

p->t, a -> i, p -> t, e -> l, r -> e true;

s里的每一个字母都映射着t里的一个字母

时间复杂度 o(N)

public class Solution {
    /**
     * @param s: a string
     * @param t: a string
     * @return: true if the characters in s can be replaced to get t or false
     */
    public boolean isIsomorphic(String s, String t) {
        // write your code here
        
        if(s.length() != t.length()){
            return false;
        }
        
        int[] S = new int[256];
        int[] T = new int[256];
        
        for (int i = 0; i < t.length(); i++ ){
            if(S[s.charAt(i)] != T[t.charAt(i)] ){
                return false;
            }
            //用i+1 而不用++是因为 i+1可以根据index把不同的映射区分开,如果是++的话,
            //有可能导致值相等的问题从而影响判断
            S[s.charAt(i)] = i+1;
            T[t.charAt(i)] = i+1;
        } 
        
        return true;
    }
}

Last updated