Short Java Solution with one map


  • 0
    A
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            HashMap<Character, Character> map = new HashMap<Character, Character>();
            if (s.length() != t.length()) return false;
            for (int i = 0; i <= s.length() - 1; i++) {
                if (map.containsKey(s.charAt(i)) == false && map.containsValue(t.charAt(i)) == false) {
                    map.put(s.charAt(i), t.charAt(i));
                } else if (map.containsKey(s.charAt(i)) == false || map.get(s.charAt(i)) != t.charAt(i)) {
                    return false;
                }
            }
            return true;
        }
    }

  • 0
    N

    use !map.containsKey(s.charAt(i)) instead of map.containsKey(s.charAt(i)) == false is a good practice


  • 0
    A

    Thanks for the advice.


Log in to reply
 

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