Java Solution with one HashMap

  • 0

    My Java Solution with one HashMap

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
           HashMap<Character,Character> myMap = new HashMap<Character,Character>(); 
            for(int i=0;i<s.length();i++) {
               if(myMap.containsKey(s.charAt(i)) && (t.charAt(i) != myMap.get(s.charAt(i)))) return false; 
               else if(!myMap.containsKey(s.charAt(i)) && myMap.containsValue(t.charAt(i)))  return false;
               else  myMap.put(s.charAt(i),t.charAt(i)); 
           return true; 

  • -1

    Time complexity of your solution will be O(n^2). If the test case is more strict, maybe this solution can not pass through.

  • 0

    In which case will the complexity be n^2 ? @caijun

  • 0

    Both containsKey and containsValue can't be O(1), unless internally HashMap stores two mapping tables.

Log in to reply

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