290. Word Pattern
- Total Accepted: 43861
- Total Submissions: 144885
- 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.
Credits:
class Solution {
public:
bool wordPattern(string pattern, string str) {
int vis[500];
memset(vis , 0, sizeof(vis));
map<int,string>mp;
map<string,int>b_mp;
vector<int>a;
vector<string>b;
for(int i=0;i<pattern.length();i++)
a.push_back(pattern[i]);
string t="";
str=str+" ";
for(int i=0;i<str.length();i++)
if(str[i]==' ')
{
b.push_back(t);
t="";
}
else
{
t=t+str[i];
}
if(a.size()!=b.size()) return false;
for(int i=0;i<a.size();i++)
{
if(!vis[a[i]])
{
if(b_mp[b[i]]) return false;
vis[a[i]]=1;
mp[a[i]]=b[i];
vis[a[i]]=1;
b_mp[b[i]]=a[i];
}
else
{
if(mp[a[i]]!=b[i]) return false;
}
}
return true;
}
};
本文介绍了一种基于WordPattern的问题解决方法,通过分析模式与字符串的一致性来判断字符串是否遵循给定的模式。该算法利用哈希映射实现模式与单词间的全匹配对照,并详细解释了其实现过程及关键步骤。
508

被折叠的 条评论
为什么被折叠?



