Given a pattern and a string s
, find if s
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s
.
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
1 <= pattern.length <= 300
pattern
contains only lower-case English letters.1 <= s.length <= 3000
s
contains only lowercase English letters and spaces.s
does not contain any leading or trailing spaces.s
are separated by a single space.s
?
s
is well-formatted with a single space separating the words.s
contains only lowercase English letters.s
or pattern
possible?
pattern
is between 1 and 300 and s
between 1 and 3000.s
into individual words.pattern
and the list of words derived from s
. If they do not match, return false
.patternToWord
to map each character in the pattern to a corresponding word in s
.wordToPattern
to map each word in s
to a corresponding character in the pattern.pattern
and the words simultaneously:
false
.true
.#include <iostream>
#include <unordered_map>
#include <vector>
#include <sstream>
using namespace std;
bool wordPattern(string pattern, string s) {
// Split s into words
vector<string> words;
stringstream ss(s);
string word;
while (ss >> word) {
words.push_back(word);
}
// If pattern length and words' length doesn't match
if (pattern.length() != words.size()) return false;
unordered_map<char, string> patternToWord;
unordered_map<string, char> wordToPattern;
for (int i = 0; i < pattern.length(); i++) {
char p = pattern[i];
string w = words[i];
// Check if there is a conflict in pattern to word mapping
if (patternToWord.count(p) > 0 && patternToWord[p] != w) return false;
if (wordToPattern.count(w) > 0 && wordToPattern[w] != p) return false;
// Establish new mapping
patternToWord[p] = w;
wordToPattern[w] = p;
}
return true;
}
int main() {
string pattern = "abba";
string s = "dog cat cat dog";
cout << (wordPattern(pattern, s) ? "true" : "false") << endl; // Output: true
return 0;
}
s
: O(n), where n
is the length of s
.m
is the length of the pattern.m
is significantly smaller than n
.This code and strategy ensure the solution is efficient and clear.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?