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;
    }
};
相关推荐
纵有疾風起17 分钟前
C++——类和对象(3)
开发语言·c++·经验分享·开源
丁浩6661 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
承渊政道2 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
best_virtuoso2 小时前
PostgreSQL 常见数组操作函数语法、功能
java·数据结构·postgresql
孤独得猿2 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
伏小白白白2 小时前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
new coder2 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
无敌最俊朗@3 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
囚生CY3 小时前
【速写】优化的深度与广度(Adam & Moun)
人工智能·python·算法
哼?~3 小时前
C++11标准 上 (万字解析)
开发语言·c++