Java solution with HashMap with short explaination


  • 0
    X
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            if(s.equals(t)){
                return true;
            }
            if(s.length() != t.length()){
                return false;
            }
            if(s == null && t == null){
                return false;
            }
            HashMap<Character, Character> map = new HashMap<Character, Character>();
            char[] s_array = s.toCharArray();
            char[] t_array = t.toCharArray();
            for(int i = 0; i < s_array.length; i++){
                if(!map.containsKey(s_array[i])){ // if map does not contain current key
                    if(map.containsValue(t_array[i])){ // if the current value has been mapped by other keys
                        return false;
                    }
                    map.put(s_array[i], t_array[i]);
                }else{ // if map contains current key, judge whether current value equals the mapped value
                    if(!(map.get(s_array[i]) == t_array[i])){
                        return false;
                    }
                }
            }
            return true;        
        }
    }

  • 0
    L

    Replace HashMap to arrays to increase the performance.

    Solution 8ms - O(n)

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            if(s.length() != t.length()) return false;
    
            int N = s.length();
            int[] mst = new int[256];
            int[] mts = new int[256];
            
            for(int i = 0; i < N; i++) {
                char cs = s.charAt(i);
                char ct = t.charAt(i);
                
                if((mst[cs] == 0) && (mts[ct] == 0)) {
                    mst[cs] = ct;
                    mts[ct] = cs;
                }
                
                if((mst[cs] != ct) || (mts[ct] != cs)) 
                    return false;
            }
            
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.