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


最新文章

  1. iOS-数据持久化详细介绍
  2. IOS 日期的简洁格式展示
  3. HttpWebRequest-header设置
  4. QlikView 权限设置问题和注意
  5. Struts2注解使用说明
  6. [转载] 使用MySQL Proxy解决MySQL主从同步延迟
  7. absolute绝对定位可以实现相对定位
  8. Poj(2407),Greater New York Regional 2015 (D)
  9. mybatis insert前获取要插入的值
  10. pen: Local Testing
  11. android Service简介及启动关闭方式
  12. javaWEB总结(11):JSP简介及原理
  13. Unity编程标准导引-1.2官方资源介绍
  14. 设计模式——模板模式(C++实现)
  15. 2015 多校联赛 ——HDU5303(贪心)
  16. 查看和设置MySQL数据库字符集(转)
  17. wx 参数传值
  18. ORACLE环境变量定义
  19. 客户端负载均衡Feign之一:申明式服务调用Feign入门示例
  20. Math类的三个方法比较: floor() ceil() round()

热门文章

  1. python__007内置函数
  2. 【推荐算法工程师技术栈系列】程序语言--Java
  3. Java中File类的基本用法
  4. HTML5 plus 报错 Uncaught SyntaxError: Unexpected identifier at XXXX.html:1
  5. xampp:windows找不到文件“-n”
  6. SQL修改数据表字段长度
  7. 红帽学习笔记[RHCSA] 第二周
  8. 运维日常之机房浪潮服务器硬盘红灯亮起,服务器一直响,raid磁盘红色。。。故障解决方法
  9. Python的入门(day1)
  10. [转帖]2017年新闻: 中国CPU还在“群雄割据” ,印度已确定了国家指令集