Two pass with one HashMap


  • 0
    V

    onePass only validates whether source can be translated into target, which does not necessarily lead to the conclusion source and target are isomorphic. But it does if target can be translated into source as well.

    public boolean isIsomorphic(String s, String t) {
        return onePass(s,t) && onePass(t,s);
    }
    
    public boolean onePass(String s, String t)
    {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        for(int i = 0; i < s.length(); i++)
        {
            char cs = s.charAt(i);
            char ct = t.charAt(i);
            if(!map.containsKey(cs)){
                map.put(cs, ct);
            }else{
                if(map.get(cs) != ct)
                    return false;
            }
        }
        return true;
    }

  • 0
    L

    Not work for test case: s="ab", t="aa". A little modification:

    public boolean onePass(String s, String t)
    {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        for(int i = 0; i < s.length(); i++)
        {
            char cs = s.charAt(i);
            char ct = t.charAt(i);
            if(!map.containsKey(cs)){
            //=========modified=============
                  if (!map.contains(ct){
                     map.put(cs, ct);
                   }
                  else{
                       return False;
                   }
           //=============================          
            }else{
                if(map.get(cs) != ct)
                    return false;
            }
        }
        return true;
    }

Log in to reply
 

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