Given a pattern and a string str, find if str 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 str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

这道题给我们一个模式字符串,又给我们一个单词字符串,让我们求单词字符串中单词出现的规律是否符合模式字符串中的规律。那么首先想到就是用 HashMap 来做,建立模式字符串中每个字符和单词字符串每个单词之间的映射,而且这种映射必须是一对一关系的,不能 'a' 和 'b' 同时对应 'dog',也不能 'a' 同时对应到 'dog' 和 'cat',所以我们在碰到一个新字符时,首先检查其是否在 HashMap 中出现,若出现,其映射的单词若不是此时对应的单词,则返回 false。如果没有在 HashMap 中出现,我们还要遍历一遍 HashMap,看新遇到的单词是否已经是其中的映射,若已经有其他映射,直接返回 false,如果没有,再跟新遇到的字符建立映射。最后循环退出后,要检查此时的 i 是否和 n 相同,这是检查一对一映射的最后一步,因为当 str 中的单词处理完了之后,pattern 中就不能有多余的字符了,参见代码如下:

解法一:

class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> m;
istringstream in(str);
int i = , n = pattern.size();
for (string word; in >> word; ++i) {
if (i >= n) continue;
if (m.count(pattern[i])) {
if (m[pattern[i]] != word) return false;
} else {
for (auto a : m) {
if (a.second == word) return false;
}
m[pattern[i]] = word;
}
}
return i == n;
}
};

当然这道题也可以用两个 HashMap 来完成,分别将字符和单词都映射到当前的位置加1,注意这里需要加1就是为了避免默认映射值0,因为 C++ 中的 HashMap 的机制是若访问一个不存在的 key 值,会默认建立一个映射值为0的映射。那么我们在遇到新字符和单词时,首先看 i 是否已经是 n 了,若相等了,说明此时 pattern 中的字符已经用完了,而 str 中还有多余的单词,这样是无法建立一对一映射的,直接返回 false。还有当两个 HashMap 的映射值不相同时也返回 false,否则我们同时建立单词和 pattern 字符和当前位置加1之间的映射,循环推出后还是要检测 i 是否和 n 相等,参见代码如下:

解法二:

class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, int> m1;
unordered_map<string, int> m2;
istringstream in(str);
int i = , n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || m1[pattern[i]] != m2[word]) return false;
m1[pattern[i]] = m2[word] = i + ;
}
return i == n;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/290

类似题目:

Isomorphic Strings

Word Pattern II

参考资料:

https://leetcode.com/problems/word-pattern/

https://leetcode.com/problems/word-pattern/discuss/73402/8-lines-simple-Java

https://leetcode.com/problems/word-pattern/discuss/73409/Short-C%2B%2B-read-words-on-the-fly

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Word Pattern 词语模式的更多相关文章

  1. [LeetCode] 290. Word Pattern 词语模式

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  2. [LeetCode] Word Pattern II 词语模式之二

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  3. [LeetCode] 290. Word Pattern 单词模式

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  4. [LeetCode] Word Pattern

    Word Pattern Total Accepted: 4627 Total Submissions: 17361 Difficulty: Easy Given a pattern and a st ...

  5. 290 Word Pattern 单词模式

    给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循这种模式.这里的 遵循 指完全匹配,例如在pattern里的每个字母和字符串 str 中的每个非空单词存在双向单映射关系 ...

  6. [LeetCode] 132 Pattern 132模式

    Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that  ...

  7. [LeetCode] Word Ladder 词语阶梯

    Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...

  8. [LeetCode] Word Search 词语搜索

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  9. LeetCode Word Pattern (模拟)

    题意: 给出一个模式串pattern,再给出一个串str,问str的模板是否是pattern. 思路: 注意点:只要对于所有pattern[i]相同的i,str中对应的所有words[i]也必须相同, ...

随机推荐

  1. 用SignalR 2.0开发客服系统[系列5:使用SignalR的中文简体语言包和其他技术点]

    前言 交流群:195866844 目录: 用SignalR 2.0开发客服系统[系列1:实现群发通讯] 用SignalR 2.0开发客服系统[系列2:实现聊天室] 用SignalR 2.0开发客服系统 ...

  2. ASP.NET Core 中文文档 第二章 指南(4.10)检查自动生成的Detail方法和Delete方法

    原文 Examining the Details and Delete methods 作者 Rick Anderson 翻译 谢炀(Kiler) 校对 许登洋(Seay).姚阿勇(Mr.Yao) 打 ...

  3. ASP.NET MVC——Razor视图引擎

    Razor是MVC框架视图引擎,我们今天就来说一说Razor视图引擎. 首先还是来创建一个基础项目叫Razor来演示. 先来定义一个Model叫Product public class Product ...

  4. 【原创】C#模拟Post请求,正文为json数据的代码参考

    由于之前一直在做键值对post数据的提交,没遇到过json正文的提交,遇到的问题截图: 对于此种情况的post,我用 谷歌插件 PostMan 模拟试了下成功了,截图如下: Postman插件在你选择 ...

  5. MYSQL 开发技巧

    主要涉及:JOIN .JOIN 更新.GROUP BY HAVING 数据查重/去重 1 INNER JOIN.LEFT JOIN.RIGHT JOIN.FULL JOIN(MySQL 不支持).CR ...

  6. 【夯实PHP基础】PHP的反射机制

    本文地址 分享提纲: 1. 介绍 2. 具体例子 2.1 创建Persion类 2.2 反射过程 2.3 反射后使用 1. 介绍 -- PHP5添加了一项新的功能:Reflection.这个功能使得p ...

  7. 如何注册微信小程序

    小程序是一种新的开放能力,可以在微信内被便捷地获取和传播,同时具有出色的使用体验.开发者可以根据平台提供的能力,快速地开发一个小程序. 开放内容包括: 开放注册范围:企业.政府.媒体.其他组织: 开发 ...

  8. 有了大量微信用户,就不需要App了吗?

    小卢同学是我半年前在中关村车库咖啡认识的一个自由创业者,他从北航毕业后在一家IT上市公司只上了1年多的班就辞职创业了,他的创业项目属于国内度假旅游垂直细分领域:积累大量详细的旅游攻略,组成一个个温馨舒 ...

  9. 磨刀不误砍柴工——VS生成事件

    如果说磨刀不误砍柴工,同样用好Visual Studio,会大大增加咱.NET程序猿效率.本文说的就是Visual Studio中的生成事件,在解决方案下右击某个项目然后选择 “属性” 打开窗口后即可 ...

  10. iOS:GCD组

    组内异步会与组外顺序执行的事件争抢资源 1).创建一个组 dispatch_group_t group = dispatch_group_create(); 2).组内异步ST1,DISPATCH_Q ...