Word Pattern
Total Accepted: 19405 Total Submissions: 71219 Difficulty: Easy
Given a pattern
and a string str
, find if str
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 str
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
class Solution {
public:
bool wordPattern(string pattern, string str) {
int leftIndex=0;
int rightIndex=0;
int len=pattern.length();
int len1=str.length();
map<char,string> ma;
map<char,string>::iterator it;
map<string,char> ma1;
map<string,char>::iterator it1;
for(int i=0;i<len;i++){
while(rightIndex<len1&&str[rightIndex]!=' '){
rightIndex++;
}
if(rightIndex==leftIndex){
return false;
}
string temp=str.substr(leftIndex,rightIndex-leftIndex);
if((it=ma.find(pattern[i]))!=ma.end()){
if(it->second!=temp){
return false;
}
}else{
ma[pattern[i]]=temp;
}
leftIndex=++rightIndex;
if((it1=ma1.find(temp))!=ma1.end()){
if(it1->second!=pattern[i]){
return false;
}
}else{
ma1[temp]=pattern[i];
}
}
if(rightIndex<len1){
return false;
}
return true;
}
};