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;
    }
};
相关推荐
玖釉-9 分钟前
[Vulkan 学习之路] 11 - 组装流水线:固定功能阶段 (Fixed Functions)
c++·windows·图形渲染
f狐0狸x16 分钟前
【C++修炼之路】C++string的用法
开发语言·c++·string
阿豪只会阿巴19 分钟前
【多喝热水系列】从零开始的ROS2之旅——Day9 初识话题通信:基本命令
c++·笔记·python·ubuntu·ros2
Xの哲學20 分钟前
Linux Tasklet 深度剖析: 从设计思想到底层实现
linux·网络·算法·架构·边缘计算
Imxyk31 分钟前
力扣:1553. 吃掉 N 个橘子的最少天数(记忆化搜索,Dijkstra解法)
算法
爱编码的傅同学1 小时前
【今日算法】Leetcode 581.最短无序连续子数组 和 42.接雨水
数据结构·算法·leetcode
码小猿的CPP工坊1 小时前
C++弱引用智能指针std::weak_ptr使用介绍
开发语言·c++
Σίσυφος19001 小时前
线性与非线性 、齐次非齐次
算法
暮色_年华1 小时前
随想3:关于语音采集线程 使用 CFS 调度或者 SCHED_FIFO 的思考
c++
Flash.kkl1 小时前
Linux——线程的同步和互斥
linux·开发语言·c++