My Java solution with Map and byte array


  • 0
    Q
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
    		Map<Character, Character> mapping = new HashMap<Character, Character>();
    		byte[] ch2vals = new byte[256]; //assume ascii
    		for (int i=0;i<s.length();i++){
    			char ch1 = s.charAt(i);
    			char ch2 = t.charAt(i);
    			Character val = mapping.get(ch1);
    			if (val!=null ){
    			    if ( val  != ch2){
    				    return false;
    			    }
    			    continue;
    			}
    			if(ch2vals[ch2]==1){
    				return false;
    			}
    			mapping.put(ch1, ch2);
    			ch2vals[ch2]=1;
    		}
    		return true;
        }
    }

  • -1
    N

    You can use one single HashMap with having an extra byte array !

    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; 
        }
    }

  • 0
    Q

    Yes I can. Performance of myMap.containsValue() is very questionable though.


Log in to reply
 

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