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.
Subscribe to see which companies asked this question
解题
定义HashMap
public class Solution { public boolean isIsomorphic(String s, String t) { if(s==null || t ==null) return false; if(s.length()!=s.length()) return false; if(s==null && t == null) return true; HashMap<Character,Character> map = new HashMap<Character,Character>(); for(int i = 0;i< s.length();i++){ char c1 = s.charAt(i); char c2 = t.charAt(i); Character c = getKey(map,c2); if(c !=null && c!=c1) return false; else if(map.containsKey(c1)){ if(c2!=map.get(c1)) return false; }else{ map.put(c1,c2); } } return true; } public Character getKey(HashMap<Character,Character> map,Character target){ for(Map.Entry<Character,Character> entry:map.entrySet()){ if(entry.getValue().equals(target)){ return entry.getKey(); } } return null; } }
或者
public class Solution { public boolean isIsomorphic(String s, String t) { if(s==null || t ==null) return false; if(s.length()!=s.length()) return false; if(s==null && t == null) return true; HashMap<Character,Character> map = new HashMap<Character,Character>(); for(int i = 0;i< s.length();i++){ char c1 = s.charAt(i); char c2 = t.charAt(i); Character c = map.get(c1); // key c1 value c2 if(map.containsKey(c1)){ if(map.get(c1).equals(c2)) continue; else return false; }else{ if(!map.containsValue(c2)) map.put(c1,c2); else return false; } } return true; } }
这里的字符串都是字母,前256个字符,将其映射到后256个字符
public class Solution { public boolean isIsomorphic(String s, String t) { if(s==null || t ==null) return false; if(s.length()!=s.length()) return false; if(s==null && t == null) return true; int[] m = new int[512]; for (int i = 0; i < s.length(); i++) { if (m[s.charAt(i)] != m[t.charAt(i)+256]) return false; m[s.charAt(i)] = m[t.charAt(i)+256] = i+1; } return true; } }