今天调了很久,终于笨方法调出来了。改天有空了优化一下。
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;
}
};
本文深入探讨了WordPattern问题的解决方法,通过双哈希映射实现字符串与模式的全匹配验证,确保字母与非空单词间存在一一对应关系。文章详细介绍了算法的设计思路与实现细节,包括如何处理输入字符串和模式,以及如何使用哈希映射进行匹配验证。
2862

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



