【1337code ez series】Isomorphic问题

Posted on 2018-01-29 21:07  Unkn0wnnnnn  阅读(103)  评论(0)    收藏  举报

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.

其实这道题和最长子字符串的整体思路有一定的相似,根据ASCII码用只有256个字符,使用两个数组分别记录所出现的字符,类似于一个Hashmap一对一映射的方法,就可以实现两个字符串是否同构的比对。具体实现源码如下:

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