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;
    }
};
相关推荐
骇城迷影27 分钟前
代码随想录:哈希表篇
算法·哈希算法·散列表
智者知已应修善业37 分钟前
【PAT乙级真题解惑1012数字分类】2025-3-29
c语言·c++·经验分享·笔记·算法
每天要多喝水1 小时前
动态规划Day30:买卖股票
算法·动态规划
v_for_van1 小时前
力扣刷题记录6(无算法背景,纯C语言)
c语言·算法·leetcode
-To be number.wan1 小时前
算法学习日记 | 双指针
c++·学习·算法
样例过了就是过了2 小时前
LeetCode热题100 最大子数组和
数据结构·算法·leetcode
wangluoqi2 小时前
c++ 逆元 小总结
开发语言·c++
BackCatK Chen2 小时前
第十五章 吃透C语言结构与数据形式:struct/union/typedef全解析
c语言·开发语言·数据结构·typedef·结构体·函数指针·联合体
瓦特what?2 小时前
插 入 排 序
开发语言·c++
铸人2 小时前
再论自然数全加和 - 欧拉伽马常数
数学·算法·数论·复数