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.
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 if(s == null || t == null || s.length() != t.length()) return false; 4 int len = s.length(); 5 HashMap<Character, Character> sTot = new HashMap<Character, Character> (); 6 HashMap<Character, Character> tTos = new HashMap<Character, Character> (); 7 for(int i = 0; i < len; i ++){ 8 char sc = s.charAt(i); 9 char tc = t.charAt(i); 10 if(!sTot.containsKey(sc)){ 11 sTot.put(sc, tc); 12 }else{ 13 if(sTot.get(sc) != tc) return false; 14 } 15 //take care case: ab & aa 16 if(!tTos.containsKey(tc)){ 17 tTos.put(tc, sc); 18 }else{ 19 if(tTos.get(tc) != sc) return false; 20 } 21 } 22 return true; 23 } 24 }