java solution using map with comments

  • 0
    class Solution {
    	public boolean isIsomorphic(String s, String t) {
    		Map<String, String> map = new HashMap<>();
    		String answer = "";
            //If length of both strings is diff, they cannot be converted to each other so return false.
    		if (s.length() != t.length()) {
    			return false;
            //loop through all the elements in String s
    		for (int i = 0; i < s.length(); i++) {
    			String temp = "";
                // check if the current element is present in map, if yes what is the substitution value of that string.
    			if (map.containsKey(Character.toString(s.charAt(i)))) {
    				temp = map.get(Character.toString(s.charAt(i)));
                    // if the substitution value is not equal to value in string t, return false.
    				if (!temp.equals(Character.toString(t.charAt(i)))) {
    					return false;
                // this else if will save us a lot of time, since it checks if the key(element of Stirng s) is not there 
                //and value is there (element of stirng t) then return false.
    			}else if (map.containsValue(Character.toString(t.charAt(i)))){
    				return false;
                // if map have no associated key and value then add it to map.
    			else {
    		return true;

Log in to reply

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