Isomorphic Strings

时间:2015-07-07 19:34:55   收藏:0   阅读:109

解决问题的思路:将两个字符串的模式抽出来研究。下面举例说明如何抽出一个字符串的模式。
对于paper,用1表示p,用2表示a,用3表示e,用4表示r
那么paper的模式为12134。
对于title,用1表示t,用2表示i,用3表示l,用4表示e
那么title的模式为12134。
所以同构。

编程实现中的数据结构:map

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        map<char, int> mapS1;
        int counterS1 = 0;
        for(string::iterator iter = s.begin(); iter != s.end(); iter++) {
            if(!mapS1.count(*iter)) {
                counterS1++;
                mapS1[*iter] = counterS1;
            }
        }
        vector<int> arrS1;
        for(string::iterator iter = s.begin(); iter != s.end(); iter++) {
            arrS1.push_back(mapS1[*iter]);
        }


        map<char, int> mapS2;
        int counterS2 = 0;
        for(string::iterator iter = t.begin(); iter != t.end(); iter++) {
            if(!mapS2.count(*iter)) {
                counterS2++;
                mapS2[*iter] = counterS2;
            }
        }
        vector<int> arrS2;
        for(string::iterator iter = t.begin(); iter != t.end(); iter++) {
            arrS2.push_back(mapS2[*iter]);
        }


        vector<int>::iterator iterS1, iterS2;
        iterS1 = arrS1.begin();
        iterS2 = arrS2.begin();
        for(; iterS1 != arrS1.end(); ) {
            if(*iterS1 != *iterS2)
                return false;
            iterS1++;
            iterS2++;
        }
        return true;

    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!