[LeetCode] 290. Word Pattern 单词模式
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 单词模式的更多相关文章
- [LeetCode] 290. Word Pattern 词语模式
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- 290 Word Pattern 单词模式
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循这种模式.这里的 遵循 指完全匹配,例如在pattern里的每个字母和字符串 str 中的每个非空单词存在双向单映射关系 ...
- leetcode 290. Word Pattern 、lintcode 829. Word Pattern II
290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...
- LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)
翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...
- 290. Word Pattern 单词匹配模式
[抄题]: Given a pattern and a string str, find if str follows the same pattern. Here follow means a fu ...
- LeetCode 290. Word Pattern (词语模式)
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- [leetcode] 290. Word Pattern (easy)
原题 思路: 建立两个哈希表,分别保存: 1 模式 :单词 2 单词 :是否出现过 水题 /** * @param {string} pattern * @param {string} str * @ ...
- LeetCode 290 Word Pattern
Problem: Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...
- Leetcode 290 Word Pattern STL
Leetcode 205 Isomorphic Strings的进阶版 这次是词组字符串和匹配字符串相比较是否一致 请使用map来完成模式统计 class Solution { public: boo ...
随机推荐
- 一加5安卓P刷入twrp的recovery
本文介绍的方法属于普适性的一般方法,比网上的各种工具箱会繁琐.但是工具箱不一定一直会更新(之前一加论坛的刷机工具箱已经停止更新了,估计是作者不用一加5了吧,毕竟已经好几年的手机了).并且如果你手机更新 ...
- PHP——file_put_contents()函数
前言 作为PHP的一个内置函数,他的作用就是将一个字符串写入文件 简介 使用 换行和追加写入 file_put_contents('./relation/bind.txt', $val['id'].' ...
- JAVA项目部署(1)
之前小菜觉得项目发布啊部署可难了,今个儿小菜接有幸触了一下java项目的打包和部署,没上手前觉得可高大上了,可难了,小菜这人就是做没做过的事前特别喜欢自己吓唬自己,这个习惯不好,得改!其实自己真正动手 ...
- SOA与ESB,微服务与API网关
SOA与ESB,微服务与API网关 SOA: ESB: 微服务: API网关: 参考资料: 1.漫画微服务,http://www.sohu.com/a/221400925_100039689 2.SO ...
- Windows10 Faster R-CNN(GPU版) 运行 Demo
上篇文章介绍了 TensorFlow 环境的搭建,这篇介绍 demo 运行 参考链接 参考链接2 1. 下载 TensorFlow object detection API 相关文件 点击跳转下载文件 ...
- ROM
ROM 是 read only memory的简称,表示只读存储器,是一种半导体存储器.只读存储器(ROM)是一种在正常工作时其存储的数据固定不变,其中的数据只能读出,不能写入,即使断电也能够保留数据 ...
- Xamarin Forms 实现发送通知点击跳转
1. Ensure the you have set LaunchMode.SingleTop on your MainActivity: LaunchMode.SingleTop [Activity ...
- [RN] React Native 实现 FlatList上拉加载
FlatList可以利用官方组件 RefreshControl实现下拉刷新功能,但官方没有提供相应的上拉加载的组件,因此在RN中实现上拉加载比下拉刷新要复杂一点. 不过我们仍可以通过FlatList ...
- 一篇文章了解Github和Git教程
有趣有内涵的文章第一时间送达! 喝酒I创作I分享 关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 本篇文章同步微信公众号 欢迎大家关注我的微信公众号:「醉翁猫咪」 生活中总有些东 ...
- VS2017 Asp.Net调式闪退处理