856. 句子相似性

856. 句子相似性

  给出两个句子 words1 和 words2 (每个用一个字符串数组表示),和一个相似词对数组 pairs ,你需要判断两个句子是否相似。 例如,如果相似词对是 pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]] ,那么 words1 = great acting skills 和 words2 = fine drama talent 是相似的。 需要注意,相似关系是不可传递的。例如,如果"great"和"fine"相似,"fine"和"good"相似,"great"和"good" 不是 一定相似的。 然而,相似性是对称的。例如,"great"和"fine"相似,则"fine"和"great"也是相似的,这两者是等价的。 另外,一个单词永远与它本身相似。例如,句子 words1 = ["great"], words2 = ["great"], pairs = [] 是相似的,尽管没有相似词对。 最后,两个句子只有在单词数相等的情况下才可能相似。所以,句子 words1 = ["great"] 永远不可能与句子 words2 = ["doubleplus","good"] 相似。

样例

样例1 输入: words1 = ["great","acting","skills"], words2 = ["fine","drama","talent"] and pairs = [["great","fine"],["drama","acting"],["skills","talent"]] 输出: true 解释: "great"和"fine"相似 "acting"和"drama"相似 "skills"和"talent"相似 样例2 输入: words1 = ["fine","skills","acting"], words2 = ["fine","drama","talent"] and pairs = [["great","fine"],["drama","acting"],["skills","talent"]] 输出: false 解释: "fine"和"fine"相同 "skills"和"drama"不相似 "acting"和"talent"不相似

注意事项

  1. words1和words2的长度不会超过1000。
  2. pairs的长度不会超过2000。
  3. 每一个pairs[i]的长度是2。
  4. 每一个words[i]和pairs[i][j]的长度在[1, 20]范围内。
  public class Solution {     /**      * @param words1: a list of string      * @param words2: a list of string      * @param pairs: a list of string pairs      * @return: return a boolean, denote whether two sentences are similar or not      */     public boolean isSentenceSimilarity(String[] words1, String[] words2, List<List<String>> pairs) {         // write your code here        if (words1.length != words2.length) return false;             HashSet<String> hashMap = new HashSet<>();             for (List<String> list : pairs) {                 hashMap.add(list.get(0)+list.get(1));                 hashMap.add(list.get(1)+list.get(0));             }             for (int i = 0; i < words1.length; i++) {                 if (hashMap.contains(words1[i]+words2[i])                         || words1[i].equals(words2[i])) {                     continue;                 }                 // System.out.println(words1[i]+","+words2[i]);                return false;         }            return true;     } }  
上一篇:Qt开源作品2-视频流播放vlc内核


下一篇:RepVGG: Making VGG-style ConvNets Great Again阅读分享(keras实现)