#include <frequently-used-code-snippets.h>
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words = splitString(str);
if (words.size() != pattern.length()) {
return false;
}
map<char, string> mapA;
map<string, char> mapB;
for (int i = 0; i < words.size(); i++) {
char c = pattern[i];
string word = words[i];
int result = matchBijection(mapA, mapB, c, word);
if (result == 1) {
continue;
}
if (result == 0) {
addBijection(mapA, mapB, c, word);
}
else {
return false;
}
}
return true;
}
private:
vector<string> splitString(string str) {
str += " ";
vector<string> words;
char split = ' ';
string word = "";
for (int i = 0; i < str.length(); i++) {
char c = str[i];
if (c != split) {
word += c;
}
else {
if (word != "") {
words.push_back(word);
word = "";
}
}
}
return words;
}
int matchBijection(map<char, string>& mapA,
map<string, char>& mapB,
char c,
string word) {
if (! containsKeyInMap(mapA, c) &&
! containsKeyInMap(mapB, word)) {
return 0;
}
map<char, string>::iterator iterA = mapA.find(c);
map<string, char>::iterator iterB = mapB.find(word);
if (iterA != mapA.end() && iterA->second == word &&
iterB != mapB.end() && iterB->second == c) {
return 1;
}
return -1;
}
void addBijection(map<char, string>& mapA,
map<string, char>& mapB,
char c,
string word) {
mapA[c] = word;
mapB[word] = c;
}
};
int main() {
Solution sol;
cout << sol.wordPattern("abba", "dog cat cat dog") << endl;
cout << sol.wordPattern("abba", "dog cat cat fish") << endl;
cout << sol.wordPattern("aaaa", "dog cat cat dog") << endl;
cout << sol.wordPattern("abba", "dog dog dog dog") << endl;
}