LeetCode205. 同构字符串
一、题目描述
二、解法
class Solution { public boolean isIsomorphic(String s, String t) { if (s.length() != t.length()) return false; /** * 方法1:使用HashMap,与LeetCode290题类似 */ /* Map<Character,Character> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char key = s.charAt(i); char c = t.charAt(i); if (!map.containsKey(key)) { if (map.containsValue(c)) { return false; } map.put(key,c); }else { if (!map.get(key).equals(c)) { return false; } } } return true; */ /** * 方法2:使用数组模拟哈希表 * 思路:分别记录两个字符串每个字母上一次的映射,初始时都映射到 0 */ int[] mapS = new int[256]; int[] mapT = new int[256]; for (int i = 0; i < s.length(); i++) { if (mapS[s.charAt(i)] != mapT[t.charAt(i)]) { return false; } mapS[s.charAt(i)] = i + 1; // 方便记录映射的顺序 mapT[t.charAt(i)] = i + 1; } return true; } }