【leetcode】205. Isomorphic Strings(Python & C++)

来源:互联网 发布:西北师范大学知行诱骗 编辑:程序博客网 时间:2024/05/22 13:59

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 解题思路:

  1. 思路一:利用映射,c++中为map,Python中为字典。判断条件即为,s中一个元素不能对应t中两个元素,s中两个元素不能对应t中同一个元素。这样,进行交换s和t的位置,进行两次判断即可。

  2. 思路二:设置两个大小为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

原创粉丝点击