205. 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 Note: You may assume both s and t have the same length. // correct public boolean isIsomorphic(String s, String t) { char[] sc = s.toCharArray(); char[] tc = t.toCharArray(); int[] ms = new int[256]; int[] mt = new int[256]; Arrays.fill(ms, -1); Arrays.fill(mt, -1); for(int i = 0; i < sc.length; i++){ int is = sc[i]; int it = tc[i]; if(ms[is] != mt[it]) return false; ms[is] = i; mt[it] = i; } return true; } // wrong class Solution { public boolean isIsomorphic(String s, String t) { if(s.length() != t.length()) return false; HashMap<Character, Character> map = new HashMap<>(); for(int i = 0; i < s.length(); i++){ char charS = s.charAt(i); char charT = t.charAt(i); if(!map.containsKey(charS)){ if(!map.containsKey(charT)){ map.put(charS, charT); }else{ if(map.get(charT) != charS) return false; } } if(map.get(charS) != charT) return false; } return true; } } // Input: // "ab" // "aa" // Output: // true // Expected: // false // still wrong result 27 / 30 test cases passed. class Solution { public boolean isIsomorphic(String s, String t) { if(s.length() != t.length()) return false; HashMap<Character, Character> map = new HashMap<>(); for(int i = 0; i < s.length(); i++){ char a = s.charAt(i); char b = t.charAt(i); if(!map.containsKey(a)){ map.put(a, b); } if(!map.containsKey(b)){ map.put(b, a); } if(map.containsKey(a)){ if(b != map.get(a)) return false; } if(map.containsKey(b)){ if(a != map.get(b)) return false; } } return true; } } Input: "ab" "ca" Output: false Expected: true a - > c c - > a b - > a a - > b okay
posted on 2018-11-08 15:43 猪猪🐷 阅读(97) 评论(0) 收藏 举报
浙公网安备 33010602011771号