給定兩個字符串 s 和 t,判斷它們是否是同構的。
如果 s 中的字符可以被替換得到 t ,那么這兩個字符串是同構的。
所有出現的字符都必須用另一個字符替換,同時保留字符的順序。兩個字符不能映射到同一個字符上,但字符可以映射自己本身。
示例 1:
輸入: s = “egg”, t = “add”
輸出: true
代碼
class Solution {public boolean isIsomorphic(String s, String t) {Map<Character,Character> map=new HashMap<>();Map<Character,Character> map2=new HashMap<>();for(int i=0;i<s.length();i++){if(map.containsKey(s.charAt(i))&&t.charAt(i)!=map.get(s.charAt(i))||map2.containsKey(t.charAt(i))&&s.charAt(i)!=map2.get(t.charAt(i)))//出現一對多的情況,說明無法匹配return false;map.put(s.charAt(i),t.charAt(i));//字符串s和t的字母相互映射map2.put(t.charAt(i),s.charAt(i));}return true;}
}