Have no clue why my solution fail in last test case 29


  • 0
    S
    public class Solution {
        public boolean isIsomorphic(String s, String t) 
        {
               Map<Character, Integer> map1 = new HashMap<Character, Integer>();
              Map<Character, Integer> map2 = new HashMap<Character, Integer>();
                if(s.length()!=t.length())
                {
                    return false;
                }
                else if(s.length()>1)
                {
                     for(int i = 0; i <  s.length(); i++) 
                     {
                        Integer ord1 = map1.put(s.charAt(i), i);
                        Integer ord2 = map2.put(t.charAt(i), i);
                        if(ord1!=ord2) 
                        {
                            return false;
                        }
                    }
       
                }
              return true;
      
        }
                
    }
    

    Could not find where went wrong?
    Please review my code


  • 0
    B

    Its very tricky but I guess it is happening because of ord1 != ord2 comparison. It seems like some values are not properly unboxed.

    When I used this condition (ord1 != null && ord2 == null) || (ord1 == null && ord2 != null) || (ord1 != null && ord2 != null && ord1.intValue() != ord2.intValue()) instead of ord1 != ord2 It worked.

    Better do like this:

    Integer index = new Integer(i);
    Integer ord1 = map1.put(s.charAt(i), index);
    Integer ord2 = map2.put(t.charAt(i), index);
    
    if(ord1 != ord2)
      return false;

  • 0
    S

    Thanks for your elaborate review.Got it.


Log in to reply
 

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