描述
判断模式是否相同
解决
和前面的判断两个字符串是否同构思路一样,都是记录下位置,然后再判断。
class Solution {
public:
bool wordPattern(string pattern, string str) {
stringstream in(str);
string tmp;
vector<string> zz;
while (in >> tmp)
{
// cout << tmp << endl;
zz.push_back(tmp);
}
int length = pattern.size();
if (zz.size() != length)
return false;
map<string, int> m0;
map<char, int> m1;
for (int i = 0; i < length; ++i)
{
if (i == 0)
{
m0[zz[i]] = i + 1;
m1[pattern[i]] = i + 1;
continue;
}
if (m0[zz[i]] != m1[pattern[i]])
{
return false;
}
m0[zz[i]] = i + 1;
m1[pattern[i]] = i + 1;
}
return true;
}
};