LeetCode 205. 同构字符串(C++、python)

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

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

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

示例 1:

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

示例 2:

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

示例 3:

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

说明:
你可以假设 和 具有相同的长度。

C++

class Solution {
public:
    bool isIsomorphic(string s, string t) 
    {
        int len=s.length();
        map<char,char> dic;
        set<char> st;
        for(int i=0;i<len;i++)
        {
            if(dic.count(s[i])<1)
            {
                dic.insert(pair<char,char>(s[i],t[i]));
                st.insert(t[i]);
            }
            else if(dic[s[i]]!=t[i])
            {
                return false;
            }               
        }        
        return st.size()==dic.size();        
    }
};

python

class Solution:
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """  
        n=len(s)
        dic={}
        st=set()
        for i in range(0,n):
            if s[i] not in dic:
                dic[s[i]]=t[i]
                st.add(t[i])
            elif dic[s[i]]!=t[i]:
                return False
        return len(dic)==len(st)

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/82669650