205. Isomorphic Strings

Given two stringssandt, determine if they are isomorphic.

Two strings are isomorphic if the characters inscan be replaced to gett.

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.

For example,
Given"egg","add", return true.

Given"foo","bar", return false.

Given"paper","title", return true.

Note:
You may assume bothsandthave the same length.

注意 No two characters may map to the same character

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if (s == null && t == null) return true;
        if (s == null || t == null) return false;
        if (s.length() != t.length()) return false;

        Map<Character, Character> hash = new HashMap<>();
        for (int i = 0; i < s.length(); i++){
            char c1 = s.charAt(i);
            char c2 = t.charAt(i);

            if (!hash.containsKey(c1)){
                if (hash.containsValue(c2)) return false;
                hash.put(c1, c2);
            }
            else{
                char val = hash.get(c1);
                if (val != c2) return false;
            }
        }

        return true;
    }
}

results for ""

    No results matching ""