class Solution
{
public:
bool wordPattern(string pattern, string s)
{
unordered_map<char, string> ch2str;
unordered_map<string, char> str2ch;
int len = s.size();
int i = 0;
for (auto ch : pattern)
{
if (i > len)
{
return false;
}
int j = i;
while (j < len && s[j] != ' ') { ++j; }//分割单词
const string& tmp = s.substr(i, j - i);
if((ch2str.count(ch)&& ch2str[ch]!=tmp) || str2ch.count(tmp)&&str2ch[tmp]!=ch)
{
return false;
}
ch2str[ch] = tmp;
str2ch[tmp] = ch;
i = j + 1;
}
return i >= len;
}
};
int main()
{
Solution A;
cout << A.wordPattern("abba","dog dog dog dog") << endl;
return 0;
}
时间复杂度:O(n + m),其中 n 为 pattern 的长度,m 为 \str 的长度。插入和查询哈希表的均摊时间复杂度均为 O(n+m)。每一个字符至多只被遍历一次
空间复杂度:O(n+m),其中 n 为 pattern 的长度,m 为 str 的长度。最坏情况下,我们需要存储 pattern 中的每一个字符和 str 中的每一个字符串