Use hashmap and hashset with JAVA


  • 0
    R

    public class Solution {
    public boolean isIsomorphic(String s, String t) {
    // similiar to word pattern
    if ((s == null || s.length() == 0) && (t == null || t.length() == 0)) return true;
    if (s == null || s.length() == 0) return false;
    if (t == null || t.length() == 0) return false;
    if (s.length() != t.length()) return false;
    HashMap<Character, Character> map = new HashMap<>();
    HashSet<Character> set = new HashSet<>();

        for (int i = 0; i < s.length(); i++) {
            char chs = s.charAt(i);
            char cht = t.charAt(i);
            if (map.containsKey(chs)) {
                if (map.get(chs) != cht) {
                    return false;
                }
            } else {
                if (set.contains(cht)) { return false; }
                map.put(chs, cht);
                set.add(cht);
            }
        }
        return true;
    }
    

    }


Log in to reply
 

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