Leetcode 290. Word law
Question stem
Given a regular pattern and a string str, judge whether str follows the same pattern.
Here, follow refers to complete matching. For example, there is a bidirectional connection between each letter in the pattern and each non-empty word in the string str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Note:
You can assume that pattern contains only lowercase letters and str contains lowercase letters separated by a single space.
answer
The pattern and the word should correspond to each other. A pattern cannot correspond to multiple words, and a word cannot correspond to multiple patterns.
In order to facilitate operation, first divide s into several strings through spaces and store them in the vector, and then create the pattern to the word and Hash table from word to pattern,
traverse pattern and compare
class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char,string> patternToString;
unordered_map<string,char> stringToPattern;
vector<string> ss;
string temp = "";
for(int i = 0 ; i < s.length() ; ++i){
if(s[i] == ' '){
ss.push_back(temp);
temp = "";
}else{
temp += s[i];
}
}
ss.push_back(temp);
if(pattern.size() != ss.size()){
return false;
}
for(int i = 0 ; i < pattern.size() ; ++i){
if(patternToString.find(pattern[i]) == patternToString.end()){
patternToString[pattern[i]] = ss[i];
if(stringToPattern.find(ss[i]) != stringToPattern.end()){
return false;
}
stringToPattern[ss[i]] = pattern[i];
}
//cout<<patternToString[pattern[i]]<<' '<<ss[i]<<endl;
if(patternToString[pattern[i]] != ss[i]){
return false;
}
}
return true;
}
};