同构字符串
单词规律
两个都是映射关系,用两张哈希表记录互相映射就可以了
同构字符串:
class Solution {
public:bool isIsomorphic(string s, string t) {//用两张哈希表做映射if(s.size()!=t.size()){return false;}unordered_map<char,char>tmap;for(int i=0;i<t.size();i++){if(tmap.find(t[i])!=tmap.end()){if(tmap[t[i]]!=s[i])return false;}else{tmap[t[i]]=s[i];}}unordered_map<char,char>smap;for(int i=0;i<s.size();i++){if(smap.find(s[i])!=smap.end()){if(smap[s[i]]!=t[i])return false;}else{smap[s[i]]=t[i];}}return true;}
};
单词规律:
class Solution {
public:bool wordPattern(string pattern, string s) {vector<string> snum;int l=0;int r=0;//先把字符串分成单词while(l<s.size()&&r<s.size()){while(s[r]==' '){r++;}while(r<s.size()&s[r]!=' '){r++;}string word(s.begin()+l,s.begin()+r);snum.push_back(word);l=r+1;}if(pattern.size()!=snum.size())return false;unordered_map<char,string>cmap;unordered_map<string,char>smap;for(int i=0;i<pattern.size();i++){if(cmap.count(pattern[i])&&cmap[pattern[i]]!=snum[i]){return false;}cmap[pattern[i]]=snum[i];if(smap.count(snum[i])&&smap[snum[i]]!=pattern[i]){return false;}smap[snum[i]]=pattern[i];}return true;}
};