|
| 1 | +--- |
| 2 | +title: LeetCode-205. Isomorphic Strings |
| 3 | +permalink: leetcode-205-isomorphic-strings |
| 4 | +date: 2017-09-12 21:33:46 |
| 5 | +tags: LeetCode |
| 6 | +copyright: true |
| 7 | +--- |
| 8 | + |
| 9 | +Given two strings s and t, determine if they are isomorphic. |
| 10 | +<!-- more --> |
| 11 | +Two strings are isomorphic if the characters in s can be replaced to get t. |
| 12 | + |
| 13 | +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. |
| 14 | +__For example,__ |
| 15 | +Given `"egg", "add"`, return `true`. |
| 16 | +Given `"foo", "bar"`, return `false`. |
| 17 | +Given `"paper", "title"`, return `true`. |
| 18 | + |
| 19 | +__Note:__ |
| 20 | +You may assume both s and t have the same length. |
| 21 | + |
| 22 | +__代码__ |
| 23 | +``` |
| 24 | +public boolean isIsomorphic(String s, String t) { |
| 25 | + if (s == null || t == null || s.length() != s.length()) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + HashMap<Character,Character> m1 = new HashMap<Character,Character>(); |
| 29 | + HashMap<Character,Character> m2 = new HashMap<Character,Character>(); |
| 30 | + for (int i = 0; i < s.length(); i++) { |
| 31 | + if (!m1.containsKey(s.charAt(i))) { |
| 32 | + if (m2.containsKey(t.charAt(i))) return false; |
| 33 | + m1.put(s.charAt(i), t.charAt(i)); |
| 34 | + m2.put(t.charAt(i), s.charAt(i)); |
| 35 | + } else { |
| 36 | + if (m1.get(s.charAt(i)) != t.charAt(i)) return false; |
| 37 | + } |
| 38 | + } |
| 39 | + return true; |
| 40 | + } |
| 41 | +``` |
0 commit comments