題目


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

Two strings s and t 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.

Example 1:

1Input: s = "egg", t = "add"
2Output: true

Example 2:

1Input: s = "foo", t = "bar"
2Output: false

Example 3: Input: s = “paper”, t = “title” Output: true

Constraints:

Constraints:

$$ \begin{array}{l} 1 <= s.length <= 5 * 10^4 \\ t.length == s.length \\ s and t consist of any valid ascii character. \end{array} $$

我的思路


同時 Loop 兩個 Array ,用兩個 HashMap 同時存已經出現過的字母最新位置,每次都比較目前字母是否已出現過。如果已經出現過是否兩個上次出現過的位子是一樣的,如果有任何不一樣就返回 False。最後如果沒有找到任何不一樣就代表一樣,返回True。

程式碼


 1class Solution {
 2    public boolean isIsomorphic(String s, String t) {
 3        HashMap<Character, Integer> cacheSCharLastPosition = new HashMap<>();
 4        HashMap<Character, Integer> cacheTCharLastPosition = new HashMap<>();
 5        
 6        char[] sCharArray = s.toCharArray();
 7        char[] tCharArray = t.toCharArray();
 8        
 9        for (int i = 0; i < s.length(); i++) {
10            char sChar = sCharArray[i];
11            char tChar = tCharArray[i];
12            
13            if ((cacheSCharLastPosition.containsKey(sChar) && cacheTCharLastPosition.containsKey(tChar))) {
14                if (!cacheSCharLastPosition.get(sChar).equals(cacheTCharLastPosition.get(tChar))) {
15                    return false;
16                }
17            } else if ((!cacheSCharLastPosition.containsKey(sChar) && cacheTCharLastPosition.containsKey(tChar)) ||
18                       (cacheSCharLastPosition.containsKey(sChar) && !cacheTCharLastPosition.containsKey(tChar))) {
19                    return false;
20            }
21            cacheSCharLastPosition.put(sChar, i);
22            cacheTCharLastPosition.put(tChar, i);           
23        }
24        return true;
25    }
26}