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;
    }
};
相关推荐
做怪小疯子8 小时前
LeetCode 热题 100——子串——和为 K 的子数组
算法·leetcode·职场和发展
zl_vslam9 小时前
SLAM中的非线性优-3D图优化之李群李代数在Opencv-PNP中的应用(四)
人工智能·opencv·算法·计算机视觉
AA陈超11 小时前
ASC学习笔记0014:手动添加一个新的属性集
c++·笔记·学习·ue5
Run_Teenage12 小时前
C++:智能指针的使用及其原理
开发语言·c++·算法
mit6.82413 小时前
二维差分+前缀和
算法
民乐团扒谱机13 小时前
自然的算法:从生物进化到智能优化 —— 遗传算法的诗意与硬核“
算法
希望有朝一日能如愿以偿13 小时前
力扣每日一题:仅含1的子串数
算法·leetcode·职场和发展
Mr_WangAndy14 小时前
C++_chapter15_C++重要知识点_auto,function,bind,decltype
c++·decltype·bind·function·可调用对象
漂流瓶jz14 小时前
SourceMap数据生成核心原理:简化字段与Base64VLQ编码
前端·javascript·算法
今天的砖很烫14 小时前
ThreadLocal 中弱引用(WeakReference)设计:为什么要 “故意” 让 Key 被回收?
jvm·算法