题目:
思路:
今天这道题,需要两个字符串之间对应,也就是需要一种映射关系。那么我们很容易就可以想到使用哈希表来解决此问题。
于是,我们就创建两个哈希表,来表示它们之间的双向映射。
对于一个模式字符,判断待判定单词有没有存在,如果存在,则判断是不是之前记录的那个单词。
同理,对于一个单词,去判断这个单词之前有没有被模式字符记录过,如果有,则判断对应的模式字符和之前的模式字符相不相等。
如果当前单词和模式字符都没有出现过,则记录,建立新的映射。
C++代码附带测试:
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<string, char> str2ch;
unordered_map<char, string> ch2str;
int m = str.length();
int i = 0;
for (auto ch : pattern) {
if (i >= m) {
return false;
}
int j = i;
while (j < m && str[j] != ' ') j++;
const string &tmp = str.substr(i, j - i);
//哈希表双映射
if (str2ch.count(tmp) && str2ch[tmp] != ch) {
return false;
}
if (ch2str.count(ch) && ch2str[ch] != tmp) {
return false;
}
//如果不存在则加入
str2ch[tmp] = ch;
ch2str[ch] = tmp;
i = j + 1;
}
return i >= m;
}
};
int main()
{
string s1 = "aabb";
string s2 = "dog cat cat dog";
Solution s;
cout<<s.wordPattern(s1,s2)<<endl;
}