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, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].

Note that the similarity relation is transitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.

Similarity is also 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].

分析:本题要得出结果难度不大,但是会遇到Time Exceed Limited的错误,因此降低时间复杂度是关键。我的解题思路比较简单,首先为paris创建字典,找出所有与指定词有直接关系的近义词。例如paris 形成的字典如下:

paris = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]],

dic   =  {'great': set(['good']), 'good': set(['great', 'fine']), 'talent': set(['skills']), 'skills': set(['talent']), 
'drama': set(['acting']), 'acting': set(['drama']), 'fine': set(['good'])}

接下来就是遍历words1和words2,遇到不相同词,直接根据key在字典中找到直接近义词,然后再利用类似广度遍历的思想,找出所有直接近义词的直接近义词,得到所有的近义词列表,再判断两个词的近义词列表是否有交集。

class Solution(object):
dic = {}
def createDict(self,paris):
self.dic = {}
for i in paris:
if self.dic.has_key(i[0]):
self.dic[i[0]].add(i[1])
else:
s = set()
s.add(i[1])
self.dic[i[0]] = s if self.dic.has_key(i[1]):
self.dic[i[1]].add(i[0])
else:
s = set()
s.add(i[0])
self.dic[i[1]] = s
def buildWordList(self,wl):
if len(wl) == 0:
return ()
s = set()
stack = []
for i in wl:
stack.append(i)
while len(stack) > 0:
v = stack.pop()
if v in s:
continue
else:
s.add(v)
for j in self.dic[v]:
stack.append(j) return s def areSentencesSimilarTwo(self, words1, words2, pairs):
"""
:type words1: List[str]
:type words2: List[str]
:type pairs: List[List[str]]
:rtype: bool
"""
if len(words1) != len(words2):
return False
self.createDict(pairs)
#print self.dic
#return
for i in range(len(words1)):
#print words1[i] ,words2[i]
if words1[i] == words2[i]:
continue
else:
s1 = set()
s2 = set()
if (self.dic.has_key(words1[i])):
s1 = self.buildWordList(self.dic[words1[i]])
if (self.dic.has_key(words2[i])):
s2 = self.buildWordList(self.dic[words2[i]])
if len(s1 & s2) == 0:
print s1,s2
print words1[i] ,words2[i]
return False return True


【leetcode】Submission Details的更多相关文章

  1. 【leetcode】893. Groups of Special-Equivalent Strings

    Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-o ...

  2. 【LeetCode】319. Bulb Switcher 解题报告(Python)

    [LeetCode]319. Bulb Switcher 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/bulb ...

  3. 【LeetCode】659. Split Array into Consecutive Subsequences 解题报告(Python)

    [LeetCode]659. Split Array into Consecutive Subsequences 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  4. 【LeetCode】556. Next Greater Element III 解题报告(Python)

    [LeetCode]556. Next Greater Element III 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人 ...

  5. 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)

    [LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...

  6. 【LeetCode】722. Remove Comments 解题报告(Python)

    [LeetCode]722. Remove Comments 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/remove-c ...

  7. 【LeetCode】154. Find Minimum in Rotated Sorted Array II 解题报告(Python)

    [LeetCode]154. Find Minimum in Rotated Sorted Array II 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...

  8. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  9. 【Leetcode】Pascal's Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

随机推荐

  1. Microsoft Remote Desktop for Mac

    因为teamviewer 又限制经常断线,所以改用 Microsoft Remote Desktop  代替,用来从mac连接远程windows 主要记录一下下载地址,因为在mac app store ...

  2. python基础-并发编程之I/O模型基础

    1. I/O模型介绍 1.1 I/O模型基础 更好的理解I/O模型,需要先回顾:同步.异步.阻塞.非阻塞 同步:执行完代码后,原地等待,直至出现结果 异步:执行完代码后,不等待,继续执行其他事务(常与 ...

  3. 手写朴素贝叶斯(naive_bayes)分类算法

    朴素贝叶斯假设各属性间相互独立,直接从已有样本中计算各种概率,以贝叶斯方程推导出预测样本的分类. 为了处理预测时样本的(类别,属性值)对未在训练样本出现,从而导致概率为0的情况,使用拉普拉斯修正(假设 ...

  4. 关于add migration 报错的问题解决方案

    The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.In ...

  5. 模板变量设置 set 和 with

    from flask import Flask,render_template app = Flask(__name__) @app.route('/') def hello_world(): ret ...

  6. 洛谷 P1809 过河问题 题解

    题面 这道题是一道贪心+DP的好题: 首先排序是一定要干的事情. 然后我们分情况处理: 1.如果剩一个人,让最小的回来接他 2.如果剩两个人,让最小的回来接,剩下的那两个人(即最大的两个人)过去,让次 ...

  7. 记一次程序从x86_64linux平台移植到armv7平台

    前言 最近接了个任务,需要把代码移植到armv7平台,搜寻相关方法,了解到可以利用交叉编译工具如:gcc-linaro-arm-linux-gnueabihf.把自己依赖的第三方库代码和自己代码分别编 ...

  8. noip2018day1-赛道修建

    题目描述 \(C\) 城将要举办一系列的赛车比赛.在比赛前,需要在城内修建 $m $条赛道. \(C\) 城一共有 \(n\) 个路口,这些路口编号为 \(1,2,-,n\)有 $n-1 $条适合于修 ...

  9. noip2013day2-华容道

    题目描述 小 \(B\) 最近迷上了华容道,可是他总是要花很长的时间才能完成一次.于是,他想到用 编程来完成华容道:给定一种局面,华容道是否根本就无法完成,如果能完成,最少需要多 少时间. 小 \(B ...

  10. D - 秋实大哥与快餐店

    秋实大哥与快餐店 Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit  ...