LeetCode 734. Sentence Similarity

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 734. Sentence Similarity相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/sentence-similarity/

题目:

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 and words2 will not exceed 1000.
  • The length of pairs will not exceed 2000.
  • The length of each pairs[i] will be 2.
  • The length of each words[i] and pairs[i][j] will be in the range [1, 20].

题解:

In order to maintain symmetric, check the word combination left ^ right, and right ^ left to see if it is in the set.

Time Complexity: O(m+n). m = words1.length. n = pairs.size().

Space: O(n).

AC Java: 

 1 class Solution {
 2     public boolean areSentencesSimilar(String[] words1, String[] words2, List<List<String>> pairs) {
 3         if(words1 == null && words2 == null){
 4             return true;
 5         }
 6         
 7         if(words1 == null || words2 == null || words1.length != words2.length){
 8             return false;
 9         }
10         
11         HashSet<String> hs = new HashSet<String>();
12         for(List<String> pair : pairs){
13             hs.add(pair.get(0) + "^" + pair.get(1));
14         }
15         
16         for(int i = 0; i<words1.length; i++){
17             if(words1[i].equals(words2[i]) ||
18               hs.contains(words1[i]+"^"+words2[i]) || 
19               hs.contains(words2[i]+"^"+words1[i])){
20                 continue;
21             }
22             
23             return false;
24         }
25         
26         return true;
27     }
28 }

类似Sentence Similarity II.

以上是关于LeetCode 734. Sentence Similarity的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Sentence Screen Fitting

Leetcode: Sentence Screen Fitting

[LeetCode] Sentence Similarity

[LeetCode] Sentence Similarity 句子相似度

[LeetCode] Sentence Similarity II 句子相似度之二

[LeetCode] Sentence Screen Fitting 调整屏幕上的句子