【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

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #d49238 }
span.s1 { color: #000000 }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }

时间: 2024-08-29 16:02:02

【leetcode】Submission Details的相关文章

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

【LeetCode】 Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. More practice: If you have figu

【leetcode】 Permutation Sequence

问题: 对于给定序列1...n,permutations共有 n!个,那么任意给定k,返回第k个permutation.0 < n < 10. 分析: 这个问题要是从最小开始直接到k,估计会超时,受10进制转换为二进制的启发,对于排列,比如 1,2,3 是第一个,那么3!= 6,所以第6个就是3,2,1.也就是说,从开始的最小的序列开始,到最大的序列,就是序列个数的阶乘数.那么在1,3 , 2的时候呢?调整一下,变成2,1,3,就可以继续. 实现: int getFactorial(int n

【LeetCode】103. Binary Tree Zigzag Level Order Traversal 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51524241 Subject 出处:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ri

【leetcode】893. Groups of Special-Equivalent Strings

Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-of-special-equivalent-strings/ 1)problem You are given an array A of strings. Two strings S and T are special-equivalent if after any number of moves,

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

【LeetCode】Pascal&#39;s Triangle

Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 这题别想用通项公式做,n choose m里面的连乘必然溢出,老老实实逐层用定义做. class Solution { public: vector<vector<

【LeetCode】Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. 思路:第一遍正常复制链表,同时用哈希表保存链表中原始节点和新节点的对应关系,第二遍遍历链表的时候,再复制随机域. 这是一种典型的空间换时间的做法,n个节点,需要大小为O(n