Simple O(n) Solution


  • 0
        public static boolean isIsomorphic(String s, String t) {
    		Map<Character,Character> hash_s = new HashMap<Character,Character>();
    		Map<Character,Character> hash_t = new HashMap<Character,Character>();
    		char[] sc = s.toCharArray();
    		char[] tc = t.toCharArray();
    		for(int i=0;i<s.length();i++) {
    			if(hash_s.containsKey(sc[i])) {
    				if(hash_s.get(sc[i])!=tc[i]) return false;
    			}
    			else {
    				hash_s.put(sc[i], tc[i]);
    			}
    			if(hash_t.containsKey(tc[i])) {
    				if(hash_t.get(tc[i])!=sc[i]) return false;
    			}
    			else {
    				hash_t.put(tc[i], sc[i]);
    			}
    		}
    		return true;
    	}

Log in to reply
 

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