Isomorphic Strings

题目
Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

答案

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s.length() != t.length()) return false;
        Map m = new HashMap<>();
        Set set = new HashSet<>();
        
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            Character cm = m.get(c);
            if(cm != null) {
                if(t.charAt(i) != cm) return false;
            }
            else {
                if(set.contains(t.charAt(i))) return false;
                m.put(c, t.charAt(i));
                set.add(t.charAt(i));
                
            }
        }
        return true;
    }
}

你可能感兴趣的:(Isomorphic Strings)