LeetCode 205 - 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.

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

Given "foo""bar", return false.

Given "paper""title", return true.

Note:
You may assume both s and t have the same length.

public boolean isIsomorphic(String s, String t) {
    if(s.length() != t.length()) return false;
    Map<Character, Character> mapS = new HashMap<>(), 
    mapT = new HashMap<>();
    
    for(int i=0; i<s.length(); i++) {
        char cs = s.charAt(i);
        char ct = t.charAt(i);
        if(!mapS.containsKey(cs)) {
            mapS.put(cs, ct);
        } else if(mapS.get(cs) != ct) {
            return false;
        }
        
        if(!mapT.containsKey(ct)) {
            mapT.put(ct, cs);
        } else if(mapT.get(ct) != cs) {
            return false;
        }
    }
    return true;
}

 

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