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.

给一个模式字符串,又给了一个单词字符串,判断单词字符串中单词出现的规律是否符合模式字符串中的规律。

解法1:哈希表。

解法2: 这个问题相当于同构字符串 205. Isomorphic Strings.

Java:

public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}  

Java:

public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length()) return false;
Map<Character, String> ps = new HashMap<>();
Map<String, Character> sp = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
if (!ps.containsKey(c)) ps.put(c, word);
else if (!ps.get(c).equals(word)) return false; if (!sp.containsKey(word)) sp.put(word, c);
else if (sp.get(word) != c) return false;
}
return true;
}
}  

Java:

public boolean wordPattern(String pattern, String str) {
String [] strArr = str.split(" ");
LinkedHashMap<String, ArrayList<Integer>> map = new LinkedHashMap<String, ArrayList<Integer>>();
LinkedHashMap<String, ArrayList<Integer>> map2 = new LinkedHashMap<String, ArrayList<Integer>>();
for(int i=0; i<pattern.length(); i++){
map.putIfAbsent(pattern.charAt(i)+"", new ArrayList<Integer>());
map.get(pattern.charAt(i)+"").add(i);
}
for(int i=0; i<strArr.length; i++){
map2.putIfAbsent(strArr[i], new ArrayList<Integer>());
map2.get(strArr[i]).add(i);
}
return new ArrayList(map.values()).equals(new ArrayList(map2.values()));
}  

Java:

public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] arr= str.split(" ");
HashMap<Character, String> map = new HashMap<Character, String>();
if(arr.length!= pattern.length())
return false;
for(int i=0; i<arr.length; i++){
char c = pattern.charAt(i);
if(map.containsKey(c)){
if(!map.get(c).equals(arr[i]))
return false;
}else{
if(map.containsValue(arr[i]))
return false;
map.put(c, arr[i]);
}
}
return true;
}
}  

Python:

# Time:  O(n)
# Space: O(n)
class Solution2(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split() # Space: O(n)
if len(pattern) != len(words):
return False w2p, p2w = {}, {}
for p, w in izip(pattern, words):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True

Python: wo

class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
s = str.split()
if len(s) != len(pattern):
return False
m1 = {}
m2 = {}
for i in xrange(len(s)):
if m1.get(pattern[i]) != m2.get(s[i]):
return False
m1[pattern[i]] = i
m2[s[i]] = i return True   

Python:

from itertools import izip  # Generator version of zip.

class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) != self.wordCount(str):
return False w2p, p2w = {}, {}
for p, w in izip(pattern, self.wordGenerator(str)):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True def wordCount(self, str):
cnt = 1 if str else 0
for c in str:
if c == ' ':
cnt += 1
return cnt # Generate a word at a time without saving all the words.
def wordGenerator(self, str):
w = ""
for c in str:
if c == ' ':
yield w
w = ""
else:
w += c
yield w

Python:

def wordPattern1(self, pattern, str):
s = pattern
t = str.split()
return map(s.find, s) == map(t.index, t) def wordPattern2(self, pattern, str):
f = lambda s: map({}.setdefault, s, range(len(s)))
return f(pattern) == f(str.split()) def wordPattern3(self, pattern, str):
s = pattern
t = str.split()
return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t)  

Python:

class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
x = str.split(' ')
lsp = len(set(pattern))
lsx = len(set(x))
return len(x)==len(pattern) and lsx==lsp and lsp== len(set(zip(pattern, x)))  

C++:  

bool wordPattern(string pattern, string str) {
map<char, int> p2i;
map<string, int> w2i;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || p2i[pattern[i]] != w2i[word])
return false;
p2i[pattern[i]] = w2i[word] = i + 1;
}
return i == n;
}

C++:

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

  

  

类似题目:  

[LeetCode] 205. Isomorphic Strings 同构字符串

[LeetCode] 291. Word Pattern II 词语模式 II

All LeetCode Questions List 题目汇总

[LeetCode] 290. 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. 290 Word Pattern 单词模式

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

  3. leetcode 290. Word Pattern 、lintcode 829. Word Pattern II

    290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...

  4. LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)

    翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...

  5. 290. Word Pattern 单词匹配模式

    [抄题]: Given a pattern and a string str, find if str follows the same pattern. Here follow means a fu ...

  6. LeetCode 290. Word Pattern (词语模式)

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

  7. [leetcode] 290. Word Pattern (easy)

    原题 思路: 建立两个哈希表,分别保存: 1 模式 :单词 2 单词 :是否出现过 水题 /** * @param {string} pattern * @param {string} str * @ ...

  8. LeetCode 290 Word Pattern

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

  9. Leetcode 290 Word Pattern STL

    Leetcode 205 Isomorphic Strings的进阶版 这次是词组字符串和匹配字符串相比较是否一致 请使用map来完成模式统计 class Solution { public: boo ...

随机推荐

  1. ThinkPHP模板之一

    这个东东,就得多练多写,无它法. 1,Application\Home\Controller\IndexController.class.php <?php namespace Home\Con ...

  2. selenium常用的API(四)设置get方法最大加载时间

    我们在进行自动化测试的时候,使用get方法打开页面时会等到页面完全加载完才会执行后续操作, 有时我们需要的元素已加载完成,而部分JS未加载完导致加载时间很长,这无疑增加了自动化测试的时间, 针对此情况 ...

  3. monkey内存泄露

    monkey内存泄露 1.内存泄露发现方法 执行monkey测试时有时会有内存泄露情况,可以进行排查 a.手机弹出out of  memory对话框--基本确定有内存泄露 b.手机没有提示但是实际有内 ...

  4. SparkSQL读写外部数据源-jext文件和table数据源的读写

    object ParquetFileTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() ...

  5. Fiddler抓包工具介绍

    Fiddler官网 https://www.telerik.com/download/fiddler Fiddler原理 当你打开Fiddler工具的时候你会发现你浏览器的代理服务器被添加了127.0 ...

  6. 转成p进制算法C语言

    今天打比赛的时候竟然下一没有想起来, 实际上是非常简单的. 举例说明: $64 = 2 \times 3^3 + 1 \times 3^2 + 3^0$ 根据秦九韶算法每次提出3,即 $3(2 \ti ...

  7. junit4的进一步探讨

    上次只是大概记录了下junit4几个常见标签的用法. 在这篇文章中,我们来进一步分析junit4的用法. 1.断言 junit4中一个很常见的用法就是断言.说到断言,大家再熟悉不过了.不过也许有的朋友 ...

  8. lxml 和 pyquery 示例 爬 卡牌

    import requests from pyquery import PyQuery as pq import json import jsonpath from lxml import etree ...

  9. MySQL 开启远程链接(localhost 以外的主机)

    1.在连接服务器后,操作mysql系统数据库 命令为:  mysql -u root -p use mysql: 查询用户表命令:select  User,authentication_string, ...

  10. BZOJ 4103: [Thu Summer Camp 2015]异或运算 可持久化trie

    开始想了一个二分+可持久化trie验证,比正解多一个 log 仔细思考,你发现你可以直接按位枚举,然后在可持久化 trie 上二分就好了. code: #include <bits/stdc++ ...