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;
    }
};
相关推荐
啊森要自信2 小时前
CANN ops-cv:AI 硬件端视觉算法推理训练的算子性能调优与实战应用详解
人工智能·算法·cann
czy87874752 小时前
深入了解 C++ 中的 `std::bind` 函数
开发语言·c++
我在人间贩卖青春2 小时前
C++之继承的方式
c++·private·public·protected·继承方式
仟濹2 小时前
算法打卡day2 (2026-02-07 周五) | 算法: DFS | 3_卡码网99_计数孤岛_DFS
算法·深度优先
驭渊的小故事2 小时前
简单模板笔记
数据结构·笔记·算法
YuTaoShao3 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法一)前后缀分解
算法·leetcode·职场和发展
VT.馒头3 小时前
【力扣】2727. 判断对象是否为空
javascript·数据结构·算法·leetcode·职场和发展
goodluckyaa3 小时前
LCR 006. 两数之和 II - 输入有序数组
算法
孤狼warrior3 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Σίσυφος19003 小时前
PCL法向量估计 之 RANSAC 平面估计法向量
算法·机器学习·平面