Leetcode290. 单词规律

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中的每一个字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值