leetcode_Isomorphic Strings _easy
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.
方法:使用2个map就可以。
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        map<char,char> ccmap,ccmap2;
        int i=s.length(),j=t.length();
        if(i==j)
        {
            for(int m=0; m<i; m++)
            {
                map<char,char>::iterator iter=ccmap.find(s[m]);
                if(iter!=ccmap.end())//找到。此字符之前已经作为原始字符在替换中用过
                {
                    if((*iter).second!=t[m])
                        return false;
                }
                else
                    ccmap[s[m]]=t[m];
            }
            //通过map推断是否存在那种aa, ba这种情况导致的多个字符映射到同一个字符的错误。假设存在,那么返回false
            int len=ccmap.size(),len2;
            //将ccmap中的key和value进行调换位置赋值给ccmap2,ccma自己不变
            for(map<char,char>::iterator iter=ccmap.begin(); iter!=ccmap.end(); iter++)
                ccmap2[(*iter).second]=(*iter).first;
            len2=ccmap2.size();
            if(len!=len2)//长度不等。那么说明ccmap中存在value相等的元素(如aa,ba: a-->b, a-->a,false)
                return false;//
            return true;
        }
        return false;
    }
};
 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号