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.

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.

class Solution {
public:
    void feature(string &s, map<char, vector<int> >& m){
        for(int i=0;i<s.size();i++){
            if(m.count(s[i]) == 0){
                vector<int> v = vector<int>();
                v.push_back(i);
                m[s[i]] = v;
            }else{
                m[s[i]].push_back(i);
            }
        }
    }
    
    bool compare(map<char, vector<int> >m, vector<int> diff){
        for (std::map<char,vector<int> >::iterator it=m.begin(); it!=m.end(); ++it){
            vector<int> &v = it->second;
            if(v.size() > 0){
                for(int i=1;i<v.size();i++){
                    if(diff[v[0]] != diff[v[i]])
                        return false;
                }
            }
        }
        return true;
    }
    bool isIsomorphic(string s, string t) {
        // You may assume both s and t have the same length.
        if(s.size() == 0) return true; 
        
        map<char, vector<int> >ms = map<char, vector<int> >();
        map<char, vector<int> >mt = map<char, vector<int> >();
        vector<int> diff = vector<int>();
        
        feature(s, ms);
        feature(t, mt);
        for(int i=0;i<s.size();i++){
            diff.push_back(s[i] - t[i]);
        }
        
        return compare(ms, diff) && compare(mt, diff);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,868评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,929评论 0 0
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,539评论 5 6
  • 今天值班,有时间写作业,却又在兜兜转转中熬到现在。不知道写什么。没有输入,也不知道该输出什么。内在有一种匮乏感。想...
    绽蕊向阳阅读 175评论 0 0
  • 你是什么? 你是穿堂风,无意驻留 你是璀璨星,闪耀暗夜 你是日复一日的美好,光芒万丈 你是这世间的温柔的存在,给我...
    涉水而歌阅读 300评论 0 1