LeetCode 290. Word Pattern
阿新 • • 發佈:2019-02-18
290. Word Pattern
class WordPattern {
public:
bool wordPattern(string pattern, string str) {
if (pattern.empty() && str.empty())
{
return true;
}
if (pattern.empty() || str.empty())
{
return false;
}
map<char , string> mc2str;
map<string, char> mstr2c;
vector<string> vstr = split(str, " ");
if (pattern.size() != vstr.size())
{
return false;
}
for (int i = 0; i < pattern.size(); i++)
{
if ((mc2str.find(pattern[i]) != mc2str.end() && mstr2c.find(vstr[i]) == mstr2c.end()) ||
(mc2str.find(pattern[i]) == mc2str.end() && mstr2c.find(vstr[i]) != mstr2c.end()))
{
return false;
}
if (mc2str.find(pattern[i]) == mc2str.end())
{
mc2str[pattern[i]] = vstr[i];
mstr2c[vstr[i]] = pattern[i];
}
else
{
if (mc2str[pattern[i]] != vstr[i])
{
return false;
}
}
}
return true;
}
vector<string> split(string str,string pattern)
{
string::size_type pos;
vector<string> result;
str += pattern;//擴充套件字串以方便操作
int size = str.size();
for(int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if(pos < size)
{
std::string s = str.substr(i, pos-i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
};