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;
    }
};
相关推荐
Espresso Macchiato几秒前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
孤寂大仙v13 分钟前
【Linux笔记】——线程同步条件变量与生产者消费者模型的实现
linux·c++·笔记
ai.Neo18 分钟前
牛客网NC276055:三根木棒能否组成三角形问题详解(ACM中的A题)
数据结构·c++·算法
_安晓29 分钟前
数据结构 -- 树形查找(三)红黑树
数据结构
じ☆ve 清风°37 分钟前
滑动窗口算法详解与C++实现
开发语言·c++·算法
苕皮蓝牙土豆42 分钟前
C++ map & multimap 容器:赋值、排序、大小与删除操作
开发语言·c++
tmacfrank44 分钟前
Android 性能优化入门(一)—— 数据结构优化
android·数据结构·性能优化
东莞呵呵1 小时前
吴恩达机器学习(1)——机器学习算法分类
算法·机器学习·分类
虾球xz1 小时前
游戏引擎学习第293天:移动Familiars
c++·学习·游戏引擎
孙同学_1 小时前
【C++】map和set的使用
开发语言·c++