[LeetCode]51. Ismorphic 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.

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.

 

解法:同构字符串,就是说原字符串中的每个字符可由另外一个字符替代,可以被其本身替代,相同的字符一定要被同一个字符替代,且一个字符不能被多个字符替代,即不能出现一对多的映射。需要考虑两种情况:t中的相同字符映射到s中后是不同的字符("aa"-->"ab");t中的不同字符映射到s中后是相同的字符("ab"-->"aa")。因此设置两个Map,一个为t在s中的映射,另一个是s在t中的映射。后者是为了检查上面所说第二种情况。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int n = s.size();
        vector<int> vt(256, -1); //t中字符在s中的映射
        vector<int> vs(256, -1); //s中字符在t中的映射
        for(int i = 0; i < n; ++i)
        {
            if(vt[t[i]] == -1) //t中当前字符还未映射过
            {
                if(vs[s[i]] == -1) //s中当前字符还未被映射过
                {
                    vt[t[i]] = s[i];
                    vs[s[i]] = t[i];
                }
                else if(vs[s[i]] != t[i]) return false; //two characters map to the same character
            }
            else if(s[i] != vt[t[i]]) return false; //a character map to two characters
        }
        return true;
    }
};

一种更简便的办法是:如果找到一对新的映射(s和t中的对应字符还没出现过),则将两个映射表的相应位置设为同一值,否则判断两个映射表的值是否相同即可。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int n = s.size();
        vector<int> vt(256, -1); //t中字符在s中的映射
        vector<int> vs(256, -1); //s中字符在t中的映射
        for(int i = 0; i < n; ++i)
        {
            //t的当前字符已经在s中映射过或者s的当前字符已经在t中映射过,并且当前的映射和之前的映射不一致
            if(vt[t[i]] != vs[s[i]]) return false;
            //找到一对全新的映射
            vt[t[i]] = i;
            vs[s[i]] = i;
        }
        return true;
    }
};

 

posted @ 2015-11-02 11:27  AprilCheny  阅读(742)  评论(0编辑  收藏  举报