美文网首页
leetcode--205--同构字符串

leetcode--205--同构字符串

作者: minningl | 来源:发表于2020-07-22 23:21 被阅读0次

    题目:
    给定两个字符串 s 和 t,判断它们是否是同构的。

    如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。

    所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

    示例 1:

    输入: s = "egg", t = "add"
    输出: true
    

    示例 2:

    输入: s = "foo", t = "bar"
    输出: false
    

    示例 3:

    输入: s = "paper", t = "title"
    输出: true
    

    说明:

    你可以假设 s 和 t 具有相同的长度。
    

    链接:https://leetcode-cn.com/problems/isomorphic-strings

    思路:
    1、同构就是说两个字符串有同样的结构,比如ABB和CDD,这就是相同的结构
    2、本解法是遍历字符串s,判断字符串s中每个元素的索引位置和t的索引位置是否相同,即可判断两字符串是否同构

    Python代码:

    class Solution(object):
        def isIsomorphic(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            for i in range(len(s)):
                if s.index(s[i]) != t.index(t[i]):
                    return False
            return True
    

    C++代码:

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            for (int i=0; i<s.size(); i++){
                if(s.find(s[i]) != t.find(t[i])){
                    return false;
                }
            }
            return true;
        }
    };
    

    相关文章

      网友评论

          本文标题:leetcode--205--同构字符串

          本文链接:https://www.haomeiwen.com/subject/akmxlktx.html