while my hashmap solution can not pass the last testcase?


  • 0
    3

    if(s.length()!=t.length()) return false;
    HashMap<Character,Integer> map_s = new HashMap<Character,Integer>();
    HashMap<Character,Integer> map_t = new HashMap<Character,Integer>();
    for(int i = 0; i < s.length(); i++){
    if(map_s.put(s.charAt(i),i)!=map_t.put(t.charAt(i),i)) return false;
    }
    return true;


  • 0
    D

    Re-formatting for readability:

    if(s.length() != t.length()) return false;
    HashMap<Character,Integer> map_s = new HashMap<Character,Integer>();
    HashMap<Character,Integer> map_t = new HashMap<Character,Integer>();
    for(int i = 0; i < s.length(); i++){
      if (map_s.put(s.charAt(i),i) != map_t.put(t.charAt(i),i)) {
        return false;
      }
    }
    return true;
    

    So you're checking if a mapping is consistent in one way (i.e. if a char source char was mapped then the destination should also get mapped, and if the source was already mapped, then the destination should also already be mapped). However, I don't see the check where you check that the mapping is consistent. Have you tried testing with this case:

    "aba" and "xyy"


Log in to reply
 

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