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;
    }
};
相关推荐
To_OC3 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵7 小时前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC9 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
郝学胜_神的一滴14 小时前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
To_OC1 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
刘马想放假2 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
05Kevin2 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员