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

51 篇文章 1 订阅
50 篇文章 28 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值