Every day a leetcode
题目来源:290. 单词规律
解法1:哈希
首先利用istringstream将字符串s按空格划分,将分割得到的单词存入数组words中。
设pattern的第i个字符为ch,数组words的第i个元素为word。
我们使用2个哈希表来判断pattern里的每个字母和字符串s中的每个非空单词之间存在着双向连接的对应规律,即双射关系。
unordered_map<char, string> umap1存储键值对:ch-word。
unordered_map<string, char> umap2存储键值对:word-ch。
遍历并判断即可。
代码:
/*
* @lc app=leetcode.cn id=290 lang=cpp
*
* [290] 单词规律
*/
// @lc code=start
class Solution
{
public:
bool wordPattern(string pattern, string s)
{
istringstream iss(s);
vector<string> words;
string word;
while (iss >> word)
words.push_back(word);
if (pattern.size() != words.size())
return false;
unordered_map<char, string> umap1;
unordered_map<string, char> umap2;
int n = pattern.size();
for (int i = 0; i < n; i++)
{
char ch = pattern[i];
word = words[i];
if (!umap1.count(ch))
umap1.insert(pair<char, string>(ch, word));
else if (umap1[ch] != word)
return false;
if (!umap2.count(word))
umap2.insert(pair<string, char>(word, ch));
else if (umap2[word] != ch)
return false;
}
return true;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n+m),其中n是pattern的长度,m为s的长度。插入和查询哈希表的均摊时间复杂度均为O(n+m)。每一个字符至多只被遍历一次。
空间复杂度:O(n+m),其中n是pattern的长度,m为s的长度。最坏情况下,我们需要存储pattern的每个字符和s中的每一个字符串。