【leetcode】Submission Details

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

 

posted @ 2017-11-30 10:04  seyjs  阅读(259)  评论(0编辑  收藏  举报