A symmetric solution with hashmap


  • 0
    B
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
         
             if(s.length()!=t.length())
               return false;
            return helper(s,t)&&helper(t,s);
           
        }
        
        public boolean helper(String s, String t)
        {
             HashMap<Character,ArrayList<Integer>> map = new HashMap<Character,ArrayList<Integer>>();
             for(int i=0;i<s.length();i++)
             {
                 if(!map.containsKey(s.charAt(i)))
                 {
                     map.put(s.charAt(i),new ArrayList<Integer>());
                     map.get(s.charAt(i)).add(i);
                 }
                 else
                 {
                     int preindex=map.get(s.charAt(i)).get(0);
                     if(t.charAt(preindex)!=t.charAt(i))
                     {
                         return false;
                     }
                 }
             }
             return true;
        }
    }
    

  • 0
    B

    @bigoffer4all

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
         
             if(s.length()!=t.length())
               return false;
            return helper(s,t)&&helper(t,s);
           
        }
        
        public boolean helper(String s, String t)
        {
            //this can be jus interger since we only remember the index of the first time we see the char
             HashMap<Character,Integer> map = new HashMap<Character,Integer>();
             for(int i=0;i<s.length();i++)
             {
                 if(!map.containsKey(s.charAt(i)))
                 {
                     //map.put(s.charAt(i),new ArrayList<Integer>());
                     map.put(s.charAt(i),i);
                 }
                 else
                 {
                     int preindex=map.get(s.charAt(i));
                     if(t.charAt(preindex)!=t.charAt(i))
                     {
                         return false;
                     }
                 }
             }
             return true;
        }
    }
    

    improvement


Log in to reply
 

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