LeetCode290. Word Pattern

文章目录

一、题目

Given a pattern and a string s, find if s 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 s.

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"

Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"

Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"

Output: false

Constraints:

1 <= pattern.length <= 300

pattern contains only lower-case English letters.

1 <= s.length <= 3000

s contains only lowercase English letters and spaces ' '.

s does not contain any leading or trailing spaces.

All the words in s are separated by a single space.

二、题解

判断一一对应:用两个哈希表

cpp 复制代码
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<char,string> map1;
        unordered_map<string,char> map2;
        istringstream iss(s);
        vector<string> tmp;
        string str;
        while(iss >> str) tmp.push_back(str);
        if(tmp.size() != pattern.size()) return false;
        for(int i = 0;i < pattern.size();i++){
            if(map1.find(pattern[i]) == map1.end()) map1[pattern[i]] = tmp[i];
            else{
                if(map1[pattern[i]] != tmp[i]) return false;
            }
            if(map2.find(tmp[i]) == map2.end()) map2[tmp[i]] = pattern[i];
            else {
                if(map2[tmp[i]] != pattern[i]) return false;
            }
        }
        return true;
    }
};
相关推荐
Laurence18 分钟前
Qt 前后端通信(QWebChannel Js / C++ 互操作):原理、示例、步骤解说
前端·javascript·c++·后端·交互·qwebchannel·互操作
王老师青少年编程25 分钟前
2026年3月GESP真题及题解(C++五级):有限不循环小数
c++·题解·真题·gesp·csp·五级·有限不循环小数
Amnesia0_027 分钟前
C++中的IO流
开发语言·c++
2401_8914821728 分钟前
C++模块化编程指南
开发语言·c++·算法
沉鱼.4428 分钟前
树、堆的题目集
算法
暮冬-  Gentle°29 分钟前
自定义类型转换机制
开发语言·c++·算法
2301_8166512241 分钟前
嵌入式C++低功耗设计
开发语言·c++·算法
机器学习之心1 小时前
PSO-LightGBM-ABKDE粒子群算法优化轻量级梯度提升机自适应带宽核密度估计多变量回归区间预测Matlab实现
算法·matlab·回归·abkde·自适应带宽核密度估计·pso-lightgbm·粒子群算法优化轻量级梯度提升机
qq_416018721 小时前
分布式缓存一致性
开发语言·c++·算法
CoovallyAIHub1 小时前
多 Agent 手术推理框架:Agent 辩论+RAG 补上手术知识,零样本超越监督基线 14.6 个百分点
算法·架构·机器人