Java Solution using char[] array and Set<Character>


  • 0
    M
    public boolean isIsomorphic(String s, String t) {
            
            if (s.length() != t.length()) {
                return false;
            }
            
            char[] s_chars = new char[256];
            Set<Character> mapped_chars_from_t = new HashSet<Character>();
            
            for (int i=0; i < s.length(); i++) {
                
                // If there is no mapping, then do the mapping
                if (s_chars[s.charAt(i)] ==  0 && !mapped_chars_from_t.contains(t.charAt(i))) {
                    s_chars[s.charAt(i)] = t.charAt(i);
                    mapped_chars_from_t.add(t.charAt(i));
                } else if (s_chars[s.charAt(i)] == t.charAt(i)) {
                    continue;
                } else if (s_chars[s.charAt(i)] != t.charAt(i) || mapped_chars_from_t.contains(t.charAt(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.