My java solution using o(n) time and o(n) space


  • 0
    C
     /*
    	 * Assumptions:
    	 * Assume that both strings are not null
    	 * Case 1: either s or t is empty, if s is empty ,then return true. if t is empty, then return false.
    	 * 
    	 * Steps: Using hashMap to save each characters in s. Each character in t will be the value of characters in s
    	 * 		  if found there is two different characters share the same key, then return false. If found one character has two
    	 * 		  keys, return false;
    	 * 	      After all characters are checked, we can return true.
    	 * 
    	 * Return a boolean to indicate whether two strings are isomophic. 
    	 * 
    	 * Time complexity:O(n)  Space complecity:O(n) 
    	 */
        
        public boolean isIsomorphic(String s, String t) {
            // Write your solution here.
    		if(s.length() != t.length()){
    			return false;
    		}
    		Map<Character, Character> map = new HashMap<> ();
    		for(int i = 0; i < s.length(); i++){
    			if(map.containsKey(s.charAt(i))){
    				if(!map.get(s.charAt(i)).equals(t.charAt(i))){
    					return false;
    				}
    			} else if(map.containsValue(t.charAt(i))){
    				return false;
    			} else {
    				map.put(s.charAt(i), t.charAt(i));
    			}
    		}
    	    return true;
        }
    

Log in to reply
 

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