【leetcode】205. Isomorphic Strings(Python & C++)
2017-08-25 21:27
489 查看
205. Isomorphic Strings
题目链接205.1 题目描述:
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.
205.2 解题思路:
思路一:利用映射,c++中为map,Python中为字典。判断条件即为,s中一个元素不能对应t中两个元素,s中两个元素不能对应t中同一个元素。这样,进行交换s和t的位置,进行两次判断即可。思路二:设置两个大小为256,初始化为-1的数组a1和a2,分别记录s和t中每个字符的坐标。循环判断,如果同一坐标i下,a1数组中s[i]位置存放的坐标与a2数组中t[i]位置存放的坐标不相同,则出现映射错误,返回FALSE。否则分别更新数组a1和a2中s[i]和t[i]位置的坐标为i。循环结束,如果没有遇到FALSE,则返回true。
205.3 C++代码:
1、思路一代码(9ms):class Solution104_1 { public: bool sub(string s, string t) { map<char, char>m1; for (int i = 0; i < s.length(); i++) { if (m1[s[i]] == NULL) m1[s[i]] = t[i]; else if (m1[s[i]] != t[i]) return false; } return true; } bool isIsomorphic(string s, string t) { return sub(s, t) && sub(t, s); } };
2、思路二代码(6ms):
class Solution104_2 { public: bool isIsomorphic(string s, string t) { vector<int>v1(256, -1); vector<int>v2(256, -1); for (int i = 0; i < s.length();i++) { if (v1[s[i]] != v2[t[i]]) return false; v1[s[i]] = i; v2[t[i]] = i; } return true; } };
205.4 Python代码:
1、思路一代码(202ms):class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ def sub(s,t): m={} for i in range(len(s)): if s[i] not in m.keys(): m[s[i]]=t[i] else: if m[s[i]]!=t[i]: return False return True return sub(s, t) and sub(t,s)
2、思路二代码(68ms):
class Solution1(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ a1=[-1]*256 a2=[-1]*256 for i in range(len(s)): if a1[ord(s[i])] != a2[ord(t[i])]: return False a1[ord(s[i])]=i a2[ord(t[i])]=i return True
相关文章推荐
- Leetcode:205. Isomorphic Strings(JAVA)
- LeetCode 205. Isomorphic Strings(C++版)
- (easy)LeetCode 205.Isomorphic Strings (*)
- LeetCode 205. Isomorphic Strings(java)
- LeetCode LeetCode 205. Isomorphic Strings(同形词)
- Leetcode:205. Isomorphic Strings (同构字符串)
- leetcode 205. Isomorphic Strings(哈希表)
- [LeetCode]--205. Isomorphic Strings(同构字符串)
- Leetcode 205. Isomorphic Strings (Easy) (cpp)
- 205.[Leetcode]Isomorphic Strings
- Leetcode#205. Isomorphic Strings
- Leetcode 205 Isomorphic Strings 同构字符串
- Leetcode - Isomorphic Strings
- LeetCode 226 Isomorphic Strings
- leetcode 205: Isomorphic Strings
- leetcode 205 Isomorphic Strings
- leetcode笔记:Isomorphic Strings
- [LeetCode]Isomorphic Strings
- [Leetcode 205, Easy] Isomorphic Strings
- leetcode题解之Isomorphic Strings