leetcode新题,另外似乎是L家面经题
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.
这里注意不能s中两个char map到t中相同char,所以同时还需要check当前t[i]是否已经对应其他char了,这样就需要两个map来保存map pair的关系
例如 ab, aa return false
1 //use hashmap to record map of (s, t) 2 public static boolean isIsomorphic(String s, String t) { 3 if(s == null && t == null) { 4 return true; 5 } 6 if(s.length() != t.length()) { 7 return false; 8 } 9 10 HashMap<Character, Character> map1 = new HashMap<Character, Character>();//s[i], t[i] 11 HashMap<Character, Character> map2 = new HashMap<Character, Character>();//t[i], s[i] 12 13 14 for(int i = 0; i < s.length(); i++){ 15 char schar = s.charAt(i); 16 char tchar = t.charAt(i); 17 18 if(!map1.containsKey(schar)){ 19 map1.put(schar, tchar); 20 }else if(map1.get(schar) != tchar) return false; // map to wrong char 21 22 //check no two map to same char in t 23 if(!map2.containsKey(tchar)){ 24 map2.put(tchar, schar); 25 }else if(map2.get(tchar) != schar) return false; 26 } 27 28 return true; 29 }
时间: 2024-10-11 00:50:05