class Solution {
private:
bool backtracking(int pIndex, int sIndex,
const string& pattern, const string& s,
unordered_map<char, string>& patternToWord,
unordered_map<string, char>& wordToPattern) {
if (pIndex == pattern.size() && sIndex == s.size()) return true;
if (pIndex >= pattern.size() || sIndex >= s.size()) return false;
char currentChar = pattern[pIndex];
for (int i = sIndex; i < s.size(); i++) {
string word = s.substr(sIndex, i - sIndex + 1);
if ((patternToWord.count(currentChar) && patternToWord[currentChar] == word)
|| (wordToPattern.count(word) && wordToPattern[word] == currentChar)) {
if (backtracking(pIndex + 1, i + 1, pattern, s, patternToWord, wordToPattern))
return true;
} else if (!patternToWord.count(currentChar) && !wordToPattern.count(word)) {
patternToWord[currentChar] = word;
wordToPattern[word] = currentChar;
if (backtracking(pIndex + 1, i + 1, pattern, s, patternToWord, wordToPattern))
return true;
patternToWord.erase(currentChar);
wordToPattern.erase(word);
}
}
return false;
}
public:
bool wordPatternMatch(string pattern, string s) {
unordered_map<char, string> patternToWord;
unordered_map<string, char> wordToPattern;
return backtracking(0, 0, pattern, s, patternToWord, wordToPattern);
}
};