31ms Java solution using HashMap


  • 0
    X
    public class Solution {
    public boolean isIsomorphic(String s, String t) {
        char[] s_array=s.toCharArray();
        char[] t_array=t.toCharArray();
        if (s_array.length!=t_array.length)
        {
            return false;
        }
        else
        {
            int i;
            boolean flag=true;
            Map sm=new HashMap();
            Map tm=new HashMap();
            for (i=0;i<s_array.length;i++)
            {
                if (sm.put(s_array[i],s_array[i])!=tm.put(t_array[i],s_array[i]))
                {
                    flag=false;
                    break;
                }
            }
            return flag;
        }
    }
    

    }


  • 1
    L

    8ms solution

    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.