leetcode734- Sentence Similarity- easy
Posted jasminemzy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode734- Sentence Similarity- easy相关的知识,希望对你有一定的参考价值。
Given two sentences words1, words2
(each represented as an array of strings), and a list of similar word pairs pairs
, determine if two sentences are similar.
For example, "great acting skills" and "fine drama talent" are similar, if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]
.
Note that the similarity relation is not transitive. For example, if "great" and "fine" are similar, and "fine" and "good" are similar, "great" and "good" are not necessarily similar.
However, similarity is symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.
Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = []
are similar, even though there are no specified similar word pairs.
Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"]
can never be similar to words2 = ["doubleplus","good"]
.
Note:
- The length of
words1
andwords2
will not exceed1000
. - The length of
pairs
will not exceed2000
. - The length of each
pairs[i]
will be2
. - The length of each
words[i]
andpairs[i][j]
will be in the range[1, 20]
.
数据结构:Map<String, Set<String>>来存储映射关系。之后检查的时候只要判断两个单词如果不相等且没映射,那就失败了。检查完都没跳出,就成功了。
细节:1.这题和同构字符串那题不一样,那个是有方向性的,不能全局建表,一定要建两个map。比如faad-cnnf,你不能说看到f-c就要全局这样互相匹配了,下面的f再对上上面的d也是合法的。所以它必须要建两个表表示双方向映射。但本题做的similar限制根据题意是全局的,所以用一个map就够了。2.建表时注意对称性,s1和s2相似那s2和s1相似。3.对比的时候注意自我相似性。就算没有任何rules,abc还是和abc相似的。4.以后Map<..., Set<...>>这种put的时候不要检查!containsKey然后开新set了,直接一行map.putIfAbsent(..., new HashSet<>());然后后面直接拿set来add即可。
实现:
class Solution { public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) { if (words1 == null || words2 == null || words1.length != words2.length) { return false; } Map<String, Set<String>> map = new HashMap<>(); for (int i = 0; i < pairs.length; i++) { String s1 = pairs[i][0]; String s2 = pairs[i][1]; map.putIfAbsent(s1, new HashSet<String>()); map.putIfAbsent(s2, new HashSet<String>()); map.get(s1).add(s2); map.get(s2).add(s1); } for (int i = 0; i < words1.length; i++) { String w1 = words1[i]; String w2 = words2[i]; if (w1.equals(w2)) { continue; } if (!map.containsKey(w1) || !map.get(w1).contains(w2)) { return false; } } return true; } }
以上是关于leetcode734- Sentence Similarity- easy的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Sentence Screen Fitting
Leetcode: Sentence Screen Fitting
[LeetCode] Sentence Similarity
[LeetCode] Sentence Similarity 句子相似度