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;
    }
};
相关推荐
じ☆冷颜〃3 小时前
黎曼几何驱动的算法与系统设计:理论、实践与跨领域应用
笔记·python·深度学习·网络协议·算法·机器学习
数据大魔方3 小时前
【期货量化实战】日内动量策略:顺势而为的短线交易法(Python源码)
开发语言·数据库·python·mysql·算法·github·程序员创富
POLITE33 小时前
Leetcode 23. 合并 K 个升序链表 (Day 12)
算法·leetcode·链表
fpcc3 小时前
C++编程实践——链式调用的实践
c++
楚来客3 小时前
AI基础概念之八:Transformer算法通俗解析
人工智能·算法·transformer
Echo_NGC22374 小时前
【神经视频编解码NVC】传统神经视频编解码完全指南:从零读懂 AI 视频压缩的基石
人工智能·深度学习·算法·机器学习·视频编解码
会员果汁4 小时前
leetcode-动态规划-买卖股票
算法·leetcode·动态规划
橘颂TA4 小时前
【剑斩OFFER】算法的暴力美学——二进制求和
算法·leetcode·哈希算法·散列表·结构与算法
bkspiderx5 小时前
C++中的volatile:从原理到实践的全面解析
开发语言·c++·volatile