今天调了很久,终于笨方法调出来了。改天有空了优化一下。
290. Word Pattern
Easy
54159FavoriteShare
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
.
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
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) {
map<char,string> mp;
map<string,char> mp1;
string temp="";
vector<string> s;
string ts="";
s.clear();
mp.clear();
int lenp=pattern.length();
int lens=str.length();
int j=0;
int p=0;
int lens1=1;
bool ans=true;
while(j<lens)
{
if(str[j]!=' ')
{
ts+=str[j];
if(j==lens-1)s.push_back(ts);
}
else
{
s.push_back(ts);
ts = "";
p++;
lens1++;
}
j++;
}
if(lens1!=lenp)return false;
for(int i=0;i<lenp;i++)
{
if(mp.find(pattern[i])==mp.end())
{
mp[pattern[i]]=s[i];
}
else
{
if(mp.at(pattern[i])!=s[i])return false;
}
if(mp1.find(s[i])==mp1.end())
{
mp1[s[i]]=pattern[i];
}
else
{
if(mp1.at(s[i])!=pattern[i])return false;
}
}
return true;
}
};