https://leetcode.com/problems/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.
Example 1:
Input: s ="egg",
t ="add"
Output: true
Example 2:
Input: s ="foo",
t ="bar"
Output: false
Example 3:
Input: s ="paper",
t ="title"
Output: true
解题思路:
需要注意的是,要用两个map。用来处理"ab"->"aa"这种情况。
class Solution { public boolean isIsomorphic(String s, String t) { if (s == null & t == null) { return true; } Map<Character, Character> s2t = new HashMap<Character, Character>(); Map<Character, Character> t2s = new HashMap<Character, Character>(); if (s.length() != t.length()) { return false; } for (int i = 0; i < s.length(); i++) { if (s2t.containsKey(s.charAt(i))) { if (s2t.get(s.charAt(i)) != t.charAt(i)) { return false; } } else { if (t2s.containsKey(t.charAt(i))) { return false; } s2t.put(s.charAt(i), t.charAt(i)); t2s.put(t.charAt(i), s.charAt(i)); } } return true; } }