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;
    }
};
相关推荐
Kurisu_红莉栖17 分钟前
c++复习——const,static字
c++
czxyvX23 分钟前
1-Qt概述
c++·qt
齐鲁大虾29 分钟前
新人编程语言选择指南
javascript·c++·python·c#
CoderMeijun43 分钟前
C++ 多线程进阶:Lambda、条件变量与死锁
c++·多线程·条件变量·lambda·死锁·生产者消费者
foundbug9991 小时前
基于混合整数规划的电池容量优化 - MATLAB实现
数据结构·算法·matlab
unicrom_深圳市由你创科技1 小时前
上位机开发常用的语言 / 框架有哪些?
c++·python·c#
自我意识的多元宇宙2 小时前
树、森林——树与二叉树的应用(哈夫曼树的构造)
数据结构
|_⊙2 小时前
C++ 智能指针
开发语言·c++
memcpy02 小时前
LeetCode 2452. 距离字典两次编辑以内的单词【暴力;字典树】中等
算法·leetcode·职场和发展
水蓝烟雨2 小时前
2071. 你可以安排的最多任务数目
数据结构·链表