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. python_面试题_DB相关问题

    1.mysql部分 问题 问题1:mysql的存储引擎 问题2:mysql的索引机制 问题3:mysql的事务以及事务隔离级别 问题4:mvcc/GAP lock是做什么的 问题5:mysql的悲观锁 ...

  2. 【PyTorch】PyTorch中的梯度累加

    PyTorch中的梯度累加 使用PyTorch实现梯度累加变相扩大batch PyTorch中在反向传播前为什么要手动将梯度清零? - Pascal的回答 - 知乎 https://www.zhihu ...

  3. node项目自动化部署--基于Jenkins,Docker,Github(2)配置节点

    上一篇文章中准备工作已经完成的差不多了 这一篇主要讲解 Jenkins 上面的相关配置 为了让代码部署到所有的子节点上 所以我们首先需要在 Jenkins 中添加我们希望代码部署到的节点 配置节点 首 ...

  4. java实现整数计算器

    计算器代码 package stack; import java.util.ArrayList; import java.util.List; import java.util.Scanner; im ...

  5. React Native 开源项目汇总

    最近闲来无事,学习了React Native开发Android APP,自我感觉RN APP的效果和Native APP比还是蛮不错,以下是找到的一些优秀源码,仅供学习参考... React Nati ...

  6. thinkphp5服务器部署遇到的问题

    candir() has been disabled for security reasons 解决办法: 进入到php的配置目录,编辑php.ini cd /usr/local/php/etcvi ...

  7. ajax异步 —— javascript

    目录 ajax是什么 原生ajax jquery ajax ajax跨域 ajax是什么 作用:不必重新加载整个页面,更新部分页面内容. 大概使用过程:通过后台提供的数据接口,ajax获取数据,动态修 ...

  8. 【总结】Android 应用测试总结

    前提 所有的功能分支已完成 启动: 1. 启动入口:桌面正常启动,最近运行启动,所有程序列表中启动,锁屏快捷启动2. 其他入口:从其他程序开启应用,从外部以文件形式打开应用(如果有)3. 退回:从其他 ...

  9. Ansible批量部署工具

    Ansible:自动化运维工具 你需要在一台机器上yum install 一个包,这时候有一个需求,比如现在有5台机同时需要装apache这个包,那么100台呢,ssh上去就太慢了,这时候就借助到了a ...

  10. web框架-(七)Django补充---models进阶操作及modelform操作

    通过之前的课程我们可以对于Django的models进行简单的操作,今天了解下进阶操作和modelform: 1. Models进阶操作 1.1 字段操作 AutoField(Field) - int ...