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. Shell编程、part4

    本节内容 1. shell函数 2. shell正则表达式 shell函数 shell中允许将一组命令集合或语句形成一段可用代码,这些代码块称为shell函数.给这段代码起个名字称为函数名,后续可以直 ...

  2. awk 控制语句if-else

    语法: 一.if (条件){语句}[else 语句] 单分支 二.if (条件){语句}else if( 条件){语句} 多分支 示例: .[root@localhost ~]# awk -F: '{ ...

  3. 20191224 Spring官方文档(Core 1.1-1.4)

    1. IoC容器 1.1.Spring IoC容器和Bean简介 org.springframework.beans和org.springframework.context包是Spring框架的IoC ...

  4. Educational Codeforces Round 64 -B(贪心)

    题目链接:https://codeforces.com/contest/1156/problem/B 题意:给一段字符串,通过变换顺序使得该字符串不包含为位置上相邻且在字母表上也相邻的情况,并输出. ...

  5. Linux 下文件句柄数的查询学习

    1. 查看 所有进程的 打开的句柄数 lsof -n|awk '{print $2}'|sort|uniq -c |sort -nr|more 效果为: 2. 查看某一个进程内的 文件信息 lsof ...

  6. 【基本优化实践】【1.4】tempdb优化

    [1]tempdb介绍 tempdb全局存储内部对象,用户对象,临时表,临时对象,以及SQL Server操作创建的存储过程.每个数据库实例只有一个tempdb,所以可能存在性能以及磁盘空间瓶颈. 各 ...

  7. java中的小知识点

    1.数据类型的相关知识点 1.1.java内置封装类的转换 java中内置的封装类Byte.Integer.Float.Double和Long都可以转换成double类型的数值:因为这些封装好的类中都 ...

  8. Css设置最优先

    input{ width: 220px !important; } css中 加上 !important 用一些前端框架,源文件修改不便时  可以这样用

  9. HDU-4219-Randomization?

    题目描述 给定一棵\(n\)个节点的树,每条边的权值为\([0,L]\)之间的随机整数,求这棵树两点之间最长距离不超过\(S\)的概率. Input 第一行三个整数\(n,L,S\) 接下来n-1行, ...

  10. json格式和对象类型的转换20170330

    (1)对象的类型转换成字符串类型(或者更确切的说是json类型的) JSONObject jo = JSONObject.fromObject(map);常见的java代码转换成json 比如:后台J ...