leetcode-290-word pattern

Problem Description:

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.

题目大意:

给定一个模式和一个字符串,判定字符串是否和模式相匹配。

Solutions:

本体和这道题很相似,只是需要对字符串做一个预处理。仔细即可

Code in C++:

class Solution {
public:
bool wordPattern(string pattern, string str) {
vector s;
helper(str,s);
map m;
map mr;
map::iterator it;
map::iterator itr;
if(pattern.length()!=s.size()) return false;
for(int i = 0; i < pattern.length(); i++)
{
it = m.find(pattern[i]);
itr = mr.find(s[i]);
if(it!=m.end()||itr!=mr.end())
{
if(m[pattern[i]]!=s[i]||mr[s[i]]!=pattern[i]) return false;
}else{
m[pattern[i]]=s[i];
mr[s[i]]=pattern[i];
}
}
return true;

}
void helper(string &str,vector<string>&s)
{
    string tem="";
    for(int i = 0;i<str.length();i++)
    {
        if(str[i]!=' ')tem+=str[i];
        else{
            s.push_back(tem);
            tem="";
        }
    }
    if(tem!="") s.push_back(tem);
}

};