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. Nginx Server 上80,443端口。http,https共存

    server{ listen 80; listen 443 ssl; server_name www.iamle.com; index index.html index.htm index.php; ...

  2. 用poi从excel文档导入数据

    import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; impo ...

  3. 【HANA系列】SAP ECLIPSE中创建ABAP项目失败原因解析

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[HANA系列]SAP ECLIPSE中创建AB ...

  4. Python_Onlineh_Hmework(基础篇,持续更新中...)

    1 递归 1.1 定义一个函数,求一个数的阶乘 def func(x): if x == 2: return 2 else: return x*func(x-1) a = func(4) print( ...

  5. Studio 3T 破解教程

    亲测可用 ,且小编一直在使用 1.创建文件studio3t.bat 并将下面这段内容复制 @echo off ECHO 重置Studio 3T的使用日期...... FOR /f "toke ...

  6. [题解][洛谷]_U75702/P5462_X龙珠_论何为字典序

    赛时嫌麻烦,没写 赛后自闭了,写了一下午 题目描述 “X龙珠”是一款益智小游戏.游戏中有 n(2|n)n(2∣n) 个编号互不相同龙珠按照给定的顺序排成一个队列,每个龙珠上面都有一个编号.每次操作时, ...

  7. Linux学习大纲(高人整理)

    1.Linux初级 1.1 OS操作系统的原理 1.2 了解常用命令 开机关机 时间管理:date cal clock 1.3 目的结构.目的管理 树形结构 tree cd 1.4 文件管理.文件查找 ...

  8. Linux命令基础#1

    系统基础 三大部件:CPU 内存 IO 1.CPU :运算器 控制器 存储器 2.内存:CPU的数据只能从内存读取,且内存数据有易失性(页面) 3.IO:控制总线 数据总线(一个IO) OS原理: O ...

  9. 利用lambda和条件表达式构造匿名递归函数

    from operator import sub, mul def make_anonymous_factorial(): """Return the value of ...

  10. Javaweb实训-宠物医院-社区宠物医院登陆页面

    <%--        Created by IntelliJ IDEA.        User: Administrator        Date: 2018/3/13        Ti ...