[leetcode]205. Isomorphic Strings 同构字符串

题目描述:


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.
给定两个字符串 s 和 t,判断它们是否是同构的。如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。


思路:


对于给出的两个字符串s,t.使用map< char, char > 建立从s[i]到t[i]的映射.对于s中的不同位置相同的字符s[i],s[j]看其对应的map[s[i]] 与map[s[j]]是否相同,若不同,则不为同构字符串;
同时还应该建立从t[i]到s[i]的映射,对于t中的不同位置相同的字符t[i],t[j]看其对应的map[t[i]] 与map[t[j]]是否相同,若不同,则不为同构字符串;
若以上两个条件都满足,则是同构字符串.
之所以使用两个map先从s到t再从t到s,是有可能存在这种情况:s=”aba”,t=”aaa”对于s中不同位置相同的字符对应t中的字符都是’a’,但这并不是同构字符串,所以增加从t到s的映射,使满足t中不同位置相同的字符对应s中的字符都相同,才能满足同构字符串的条件.
代码:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int m = s.size();
        int n = t.size();
        //如果s的长度与t的长度不同,自然不是同构字符串
        if(m != n)
            return false;

        map<char, char> mp1;
        map<char, char> mp2;
        //建立从s到t的map<char,char>
        for(int i=0; i<m; i++){
            //如果mp1中已经存在mp1[s[i]](即为s中第一个与s[i]相同的字符对应的t中的字符)
            if(mp1.find(s[i]) != mp1.end()){
                //如果s中第一个与s[i]相同的字符对应的t中的字符(mp1[s[i]])与此刻i位置的t[i]不同,则返回false
                if(mp1[s[i]] != t[i]){
                    return false;
                }else{
                    ;
                }
            //如果之前mp1中不存在mp1[s[i]],则在使mp1[s[i]]=t[i]
            }else{
                mp1[s[i]] = t[i];
            }  
        }
        //与上一个循环相似,建立从t到s的映射
        for(int i=0; i<m; i++){
            if(mp2.find(t[i])!=mp2.end()){
                if(mp2[t[i]] != s[i]){
                    return false;
                }else{
                    ;
                }
            }else{
                mp2[t[i]] = s[i];
            }  
        }
        return true;  
    }
};

猜你喜欢

转载自blog.csdn.net/Strengthennn/article/details/81840471