290. Word Pattern

本文介绍了一种用于判断字符串中单词序列是否与给定模式相匹配的算法。通过使用两个哈希映射,分别记录模式字符到整数和单词到整数的映射,实现了高效的一对一匹配检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

题目链接:


思路分析

判断一个由多个单词组成的string是否是和字母的出现顺序是相同的。

使用两个map,将字符和单词转换为int值,看是否匹配。最后对比word和char的数量是否一致。注意要将循环匹配值规定为一致。

代码
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<char, int> p2i;
        map<string, int> w2i;
        istringstream in(str);
        int i = 0, n = pattern.length();
        for(string word; in >> word; i++){
            if (p2i[pattern[i]] != w2i[word])
                return false;
            p2i[pattern[i]] = w2i[word] = i + 1;
        }
        return i==n;
    }
};

时间复杂度: O(n)
空间复杂度: O(n)


反思

对于hash table的应用。还有iostream,已经有些陌生了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值