注意一一对应即可:
class Solution {
public:
bool wordPattern(string pattern, string str) {
int i = -1, pos = 0;
unordered_map<string, char> mp;
unordered_set<char> st;
while(++i < pattern.length() && pos != string::npos) {
string s;
int nPos = str.find(' ', pos);
if(nPos != string::npos) s = str.substr(pos, nPos - pos);
else s = str.substr(pos);
if(mp.find(s) == mp.end()) {
if(st.find(pattern[i]) != st.end())
return false;
mp[s] = pattern[i];
st.insert(pattern[i]);
}
if(i != 0 && mp[s] != pattern[i])
return false;
if(nPos == string::npos) {
pos = nPos;
break;
}
pos = nPos + 1;
}
if(i != pattern.length() - 1 || pos != string::npos)
return false;
return true;
}
};