力扣290. 单词规律

文章描述了一种通过构建两个哈希表(字符到单词和单词到字符)的方法,用于检查给定字符串`s`中是否存在与模式`pattern`匹配的子串。通过遍历`pattern`并验证映射关系,判断`s`是否符合特定模式。
摘要由CSDN通过智能技术生成

哈希表

  • 思路
    • pattern 每个字符映射 s 的一个单词,使用两个 map,存放<字符 -> 单词> 和 <单词 -> 字符>,遍历 pattern 的字符,如果查找出对应的单词和字符能够匹配即符合规律;
    • 扣出 s 字符串的单词
      • // idx is the begin of the word
        // end is the right border
        int end = idx;
        while (end < size && s[end] != ' ') {
            end++;
        }
        
        // the begin and the size to get the word from s with substr
        const std::string &word = s.substr(idx, end - idx);
    • 相互验证映射关系,如果不符合,则不符合规律;
      • // word not map the char
        if (str2ch.count(word) && str2ch[word] != ch) {
            return false;
        }
        // nor the ch not map the word
        if (ch2str.count(ch) && ch2str[ch] != word) {
            return false;
        }
        
        // build the map
        str2ch[word] = ch;
        ch2str[ch] = word;

  • 完整代码:
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        std::unordered_map<char, std::string> ch2str;
        std::unordered_map<std::string, char> str2ch;

        int size = s.size();
        int idx = 0;
        for (auto ch : pattern) {
            if (idx >= size) {
                return false;
            }

            int end = idx;
            while (end < size && s[end] != ' ') {
                end++;
            }

            const std::string &word = s.substr(idx, end - idx);

            if (str2ch.count(word) && str2ch[word] != ch) {
                return false;
            }
            if (ch2str.count(ch) && ch2str[ch] != word) {
                return false;
            }

            str2ch[word] = ch;
            ch2str[ch] = word;

            idx = end + 1;
        }

        return idx >= size;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值