My O(n) Java Solution using HashMap and Set


  • 0
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            if (s == null) return t == null;
            if (s.equals("")) return t.equals("");
            Map<Character, Character> map = new HashMap<Character, Character>();
            HashSet<Character> set = new HashSet<Character>();
            char[] sArr = s.toCharArray();
            char[] tArr = t.toCharArray();
            for (int i = 0; i < sArr.length; i++){
                if (!map.containsKey(sArr[i])){
                    map.put(sArr[i], tArr[i]);
                    if (!set.add(tArr[i])) return false;
                }else
                    if (tArr[i] != map.get(sArr[i])) return false;
            }
            return true;
        }
    }

Log in to reply
 

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