Leetcode205 同构字符串

来源:互联网 发布:淘宝onlyanna真名晓颖 编辑:程序博客网 时间:2024/05/18 01:33
题意:给定两个字符串s和t,求这两个字符串是否满足同构性。即一个字符的所有出现 都能用另一个字符代替,并且顺序不能改变。

Given "egg""add", return true.

Given "foo""bar", return false.

Given "paper""title", return true.

思路:用两个哈希map<int,vector<int>>分别存储s和t中的每个字符和其出现的序号,然后找出那些有重复出现的字符,将其对应的序号都放进一个vec<vector<int>>中去,然后在新的vec里,找对应的同构字符串中和序号对应的字符是否都相等。

代码:

class Solution {public:    bool isIsomorphic(string s, string t) {       int len1 = s.length(), len2 = t.length();    if (len1 != len2)    {    return 0;    }    int i = 0,j=0;    unordered_map<int, vector<int>> map1,map2;    for (i = 0; i < len1;i++){    map1[s[i] - ' '].push_back(i);    map2[t[i] - ' '].push_back(i);    }    vector<vector<int>> vec1,vec2;    for (auto x = map1.begin(); x != map1.end();x++){    if (x->second.size()>1)    vec1.push_back(x->second);    }    for (auto y = map2.begin(); y != map2.end(); y++){    if (y->second.size()>1)    vec2.push_back(y->second);    }    for (i = 0; i < vec1.size(); i++){    for(j = 1; j < vec1[i].size(); j++){    if (t[vec1[i][j]] != t[vec1[i][j - 1]]){    return 0;    }    }    }    for (i = 0; i < vec2.size(); i++){    for (j = 1; j < vec2[i].size(); j++){    if (s[vec2[i][j]] != s[vec2[i][j - 1]]){    return 0;    }    }    }    return 1;    }};

0 0
原创粉丝点击