[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 ...
随机推荐
- 加速Github访问
Github 仓库的数据传输很慢,甚至可能导致仓库拉取失败.例如: remote: Enumerating objects: , done. remote: Counting objects: % ( ...
- Centos7 Mysql主从双机热备的实战记录
操作系统:centos7 服务器:主:172.19.242.69 从:172.19.242.70 1. 服务器 由于Mysql不同版本之间的(二进制日志)binlog格式可能会不太一样,因此最好的 ...
- $().on()的知识点
事件冒泡阶段:事件从事件目标(target)开始,往上冒泡直到页面的最上一级标签. 假设一个元素div,它有一个下级元素p.<div> <p>元素</p></ ...
- SQL操作Spark SQL--BasicSQLTestt
object BasicSQLTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() .a ...
- Java 第12次作业--你的生日
题目:计算自己的出生日期距今天多少天,再将自己的出生日期利用SimpleDateFormat类设定的格式输出显示. 代码: import java.util.*; import java.text.* ...
- python遇到动态函数---TypeError: unbound method a() must be called with A instance as first argument (got nothing instead)
TypeError: unbound method a() must be called with A instance as first argument (got nothing instead) ...
- page内置对象
- TensorFlow的GPU设置
在使用GPU版的TensorFlow跑程序的时候,如果不特殊写代码注明,程序默认是占用所有主机上的GPU,但计算过程中只会用其中一块.也就是你看着所有GPU都被占用了,以为是在GPU并行计算,但实际上 ...
- 五.python小数据池,代码块的最详细、深入剖析
一,id,is,== 在Python中,id是什么?id是内存地址,那就有人问了,什么是内存地址呢? 你只要创建一个数据(对象)那么都会在内存中开辟一个空间,将这个数据临时加在到内存中,那么这个空间是 ...
- [USACO12MAR]花盆 二分 单调队列
[USACO12MAR]花盆 二分 单调队列 存在一个长度为\(x\)的区间\([l,r]\),使得区间中最大值与最小值差至少为\(w\),求这个最小的\(x\) \(n\le 100000\),\( ...