LeetCode 205. Isomorphic Strings
原题链接在此: https://leetcode.com/problems/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.
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.
题解:
这道题用两个Map建立s和t中对应Character的关系,一个是s到t的对应,一个是t到s的对应,要注意的是要双向检测两个Map里的对应值,否则就会出现下列错误:
因为没有检查hm2,即使“aa”的第二个值 与 hm2中已有的a相同,也不会返回false。
Time Complexity: O(s.length()). Space: O(s.length()).
AC Java:
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 if(s == null && t == null){ 4 return true; 5 } 6 if(s == null || t == null){ 7 return false; 8 } 9 if(s.length() != t.length()){ 10 return false; 11 } 12 13 Map<Character, Character> hm1 = new HashMap<Character, Character>(); 14 Map<Character, Character> hm2 = new HashMap<Character, Character>(); 15 int len = s.length(); 16 for(int i = 0; i<len; i++){ 17 if(hm1.containsKey(s.charAt(i)) && hm1.get(s.charAt(i)) != t.charAt(i)){ 18 return false; 19 } 20 if(hm2.containsKey(t.charAt(i)) && hm2.get(t.charAt(i)) != s.charAt(i)){ 21 return false; 22 } 23 hm1.put(s.charAt(i), t.charAt(i)); 24 hm2.put(t.charAt(i), s.charAt(i)); 25 } 26 return true; 27 } 28 }
很多key为char的map都可以用个长度为256的array表示.
思路和上面的相同, 两个map用扫到string的index位置联系在一起.
Time Complexity: O(s.length()). Space: O(1), 256 array 长度.
AC Java:
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 if(s == null && t == null){ 4 return true; 5 } 6 if(s == null || t == null){ 7 return false; 8 } 9 if(s.length() != t.length()){ 10 return false; 11 } 12 13 int len = s.length(); 14 int [] m1 = new int[256]; 15 int [] m2 = new int[256]; 16 for(int i = 0; i<len; i++){ 17 if(m1[s.charAt(i)] != m2[t.charAt(i)]){ 18 return false; 19 } 20 m1[s.charAt(i)] = i+1; 21 m2[t.charAt(i)] = i+1; 22 } 23 return true; 24 } 25 }
AC C++:
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 if(s.size() != t.size()){ 5 return false; 6 } 7 8 int m1[256] = {0}; 9 int m2[256] = {0}; 10 int n = s.size(); 11 for(int i = 0; i < n; i++){ 12 if(m1[s[i]] != m2[t[i]]){ 13 return false; 14 } 15 16 m1[s[i]] = i + 1; 17 m2[t[i]] = i + 1; 18 } 19 20 return true; 21 } 22 };
类似Word Pattern.