Given two strings s and t, determine if they are isomorphic.html
Two strings are isomorphic if the characters in s can be replaced to get t.java
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.python
Example 1:app
Input: s = t = Output: true "egg","add"
Example 2:url
Input: s = t = Output: false"foo","bar"
Example 3:spa
Input: s = t = Output: true"paper","title"
Note:
You may assume both s and t have the same length..net
給定兩個字符串s和t,判斷它們是不是同構的。若是字符串s能夠經過字符替換的方式獲得字符串t,則稱s和t是同構的。字符的每一次出現都必須被其對應字符所替換,同時還須要保證原始順序不發生改變。兩個字符不能映射到同一個字符,可是字符能夠映射到其自己。假設兩個字符串長度相等。 code
解法1: 將字符串所有輸出成數字序列, Given "paper", return "01023". Given "isomorphic", return "0123245607". 最後在比較兩個數字是否相等。超時不能Accept。htm
解法2: 哈希表,用哈希表記錄每個字符出現的位置,若是對應的字符出現的位置不同,就返回False,到最後都同樣就返回True。也能夠只記錄最後一個字符出現的位置,由於以前出現的位置已經比較過了。blog
Java:
public class Solution { public boolean isIsomorphic(String s1, String s2) { int[] m = new int[512]; for (int i = 0; i < s1.length(); i++) { if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false; m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1; } return true; } }
Java:
class Solution { public boolean isIsomorphic(String s, String t) { int[] a = new int[256]; int[] b = new int[256]; for (int i = 0; i < 256; i++) { a[i] = b[i] = -1; } int len = s.length(); for (int i = 0; i < len; i++) { if (a[s.charAt(i)] != b[t.charAt(i)]) { return false; } a[s.charAt(i)] = b[t.charAt(i)] = i; } return true; } }
Python: wo
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ ms, mt = {}, {} for i in xrange(len(s)): if ms.get(s[i]) != mt.get(t[i]): return False ms[s[i]] = i mt[t[i]] = i return True
Python:
def isIsomorphic1(self, s, t): d1, d2 = {}, {} for i, val in enumerate(s): d1[val] = d1.get(val, []) + [i] for i, val in enumerate(t): d2[val] = d2.get(val, []) + [i] return sorted(d1.values()) == sorted(d2.values()) def isIsomorphic2(self, s, t): d1, d2 = [[] for _ in xrange(256)], [[] for _ in xrange(256)] for i, val in enumerate(s): d1[ord(val)].append(i) for i, val in enumerate(t): d2[ord(val)].append(i) return sorted(d1) == sorted(d2) def isIsomorphic3(self, s, t): return len(set(zip(s, t))) == len(set(s)) == len(set(t)) def isIsomorphic4(self, s, t): return [s.find(i) for i in s] == [t.find(j) for j in t] def isIsomorphic5(self, s, t): return map(s.find, s) == map(t.find, t) def isIsomorphic(self, s, t): d1, d2 = [0 for _ in xrange(256)], [0 for _ in xrange(256)] for i in xrange(len(s)): if d1[ord(s[i])] != d2[ord(t[i])]: return False d1[ord(s[i])] = i+1 d2[ord(t[i])] = i+1 return True
C++:
class Solution { public: bool isIsomorphic(string s, string t) { int m1[256] = {0}, m2[256] = {0}, n = s.size(); for (int i = 0; i < n; ++i) { if (m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; } };
相似題目:
[LeetCode] 290. Word Pattern 單詞模式