My accepted easy understanding Java Solution using hashtable


  • 0
    O
    public class Solution {
    public boolean isIsomorphic(String s, String t) {
    	if(s.length() == 0)
    		return true;
    	HashMap<Character, Character>map = new HashMap<Character, Character>();
    	HashSet<Character> keys = new HashSet<Character>();
    	HashSet<Character> values = new HashSet<Character>();
    	char[] chs = s.toCharArray();
    	char[] cht = t.toCharArray();
    	for (int i = 0; i < chs.length; i++) {
    		if(!keys.contains(chs[i])) {
    			if(values.contains(cht[i]))
    				return false;
    			map.put(chs[i], cht[i]);
    			keys.add(chs[i]);
    			values.add(cht[i]);
    		} else {
    			if(cht[i] != map.get(chs[i]))
    				return false;
    		}
    	}
        return true;
    }
    

    }


  • 0
    P
    public class Solution {
    public boolean isIsomorphic(String s, String t) {
        HashMap hashmap=new HashMap();
        int length=s.length();
        int i=0;
        while(i<length)
        {
          char s1=s.charAt(i);
          char t1=t.charAt(i);
         
          if(!hashmap.containsKey(s1) && !hashmap.containsValue(t1))
            hashmap.put(s1,t1);
          else
            {  if (!hashmap.containsKey(s1))
                return false;
              else
              {    
               char ts=(char) hashmap.get(s1);
               if(t1!=ts)
                  return false;
                  
              }
            }
            i++;
        }
        return true;
    }
    

    }


Log in to reply
 

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