Leetcode: Isomorphic Strings
2015-05-15 10:31
232 查看
Get idea from here
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.
Hide Tags Hash Table
Result:
Question
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.
Hide Tags Hash Table
Analysis
[code]s1, s2 are two chars if s1 has mapped char: check whether mapped char is correct else: #s1 has no corresponding char check whether s2 is the mapped char of some one else if yes: return False if no: dict1[s1]=s2, dict2[s2]=s1
Solution
Mistake taken
This solution can’t ensure that different s1 map to different s2. In this example, “a” and “b” both map to “a”. The tricky here is to create a new dict, to make sure one char maps to only one char.[code]class Solution: # @param {string} s # @param {string} t # @return {boolean} def isIsomorphic(self, s, t): dict1 = {} for i in range(len(s)): s1,s2= s[i],t[i] if s1 in dict1: if s2!=dict1[s1]: return False else: dict1[s1] = s2 return True
Result:
[code] Input: "ab", "aa" Output: true Expected: false
Correct Code
[code]class Solution: # @param {string} s # @param {string} t # @return {boolean} def isIsomorphic(self, s, t): dict1, dict2 = {}, {} for i in range(len(s)): s1,s2= s[i],t[i] if s1 in dict1: if s2!=dict1[s1]: return False else: if s2 in dict2: return False dict1[s1] = s2 dict2[s2] = s1 return True
相关文章推荐
- [LeetCode] Isomorphic Strings - 字符串操作:数组计数字符个数问题
- leetcode - Isomorphic Strings
- 205.[Leetcode]Isomorphic Strings
- LeetCode-E-Isomorphic Strings
- Isomorphic Strings leetcode 205
- leetcode--Isomorphic Strings
- [LeetCode]Isomorphic Strings
- LeetCode----Isomorphic Strings
- [Leetcode]Isomorphic Strings
- [leetcode]Isomorphic Strings
- leetcode笔记:Isomorphic Strings
- leetcode 205: Isomorphic Strings
- LeetCode之Isomorphic Strings
- LeetCode205 Isomorphic Strings同构字符串
- LeetCode题解:Isomorphic Strings
- LeetCode(44)- Isomorphic Strings
- 关于LeetCode中Isomorphic Strings一题的理解
- [leetcode]Isomorphic Strings
- leetcode--Isomorphic Strings
- LeetCode(44)- Isomorphic Strings