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);
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,170評論 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,995評論 0 0
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,665評論 5 6
  • 今天值班,有時(shí)間寫作業(yè),卻又在兜兜轉(zhuǎn)轉(zhuǎn)中熬到現(xiàn)在。不知道寫什么。沒有輸入,也不知道該輸出什么。內(nèi)在有一種匱乏感。想...
    綻蕊向陽閱讀 192評論 0 0
  • 你是什么? 你是穿堂風(fēng),無意駐留 你是璀璨星,閃耀暗夜 你是日復(fù)一日的美好,光芒萬丈 你是這世間的溫柔的存在,給我...
    涉水而歌閱讀 365評論 0 1

友情鏈接更多精彩內(nèi)容