Java Solution with one HashMap


  • 0
    N

    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
    C

    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
    L

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


  • 0
    P

    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.