其他分享
首页 > 其他分享> > 856. 句子相似性

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;     } }  

标签:great,856,words1,words2,相似,相似性,pairs,fine,句子
来源: https://blog.csdn.net/xwdrhgr/article/details/117278992