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. python打造seo必备工具-自动查询排名

    因为工作需要,利用业余时间开发的,可以查询百度排名+360排名工具,附上代码. #360搜索排名查询 # -*- coding=utf-8 -*- import requests from lxml ...

  2. SpringBoot源码分析-编译环境与新建测试模块

    建议 分析源码建议不要使用Idea或者Eclipse等IDE工具的反编译功能或者导入源码包的方式看源码,那样不能给框架的源码做注释,所以分析源码之前都得先下载源码并构建,然后在项目中新建一个Modul ...

  3. python的readline() 和readlines()

    .readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样..readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python ...

  4. Spark Partition

    分区的意义 Spark RDD 是一种分布式的数据集,由于数据量很大,因此它被切分成不同分区并存储在各个Worker节点的内存中.从而当我们对RDD进行操作时,实际上是对每个分区中的数据并行操作.Sp ...

  5. Spring之IOC(控制反转)与AOP(面向切面编程)

    控制反转——Spring通过一种称作控制反转(IoC)的技术促进了松耦合.当应用了IoC,一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象.可以认为IoC与JND ...

  6. LeetCode 1000. Minimum Cost to Merge Stones

    原题链接在这里:https://leetcode.com/problems/minimum-cost-to-merge-stones/ 题目: There are N piles of stones ...

  7. know thself

  8. Java web开发——文件夹的上传和下载

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...

  9. 通过HttpServletRequest重写+filter 添加header

    问题说明 需要做的事情比较简单,就是通过filter 重写httpservletrequest ,同时给予request 添加header 主要是通过HttpServletRequestWrapper ...

  10. 开源项目 01 HtmlAgilityPack

    using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using Syst ...