Possible the shortest Python code?


  • 1
    K
    class Solution:
        # @param {string} s
        # @return {string[]}
        def findRepeatedDnaSequences(self, s):
            dic = {}
            for i in xrange(len(s)-9):
                dic[s[i:i+10]] = dic.get(s[i:i+10], 0) + 1
            return [res for res in dic.keys() if dic[res]>1]

  • 0
    This post is deleted!

  • 0

    Not bad, but here's a shorter one:

    class Solution:
        def findRepeatedDnaSequences(self, s):
            d = {}, {}
            for i in range(len(s)-9):
                d[s[i:i+10] in d[0]][s[i:i+10]] = 1
            return list(d[1])
    

    Although I rewrote it like that just for comparison/shortness. Originally it looked like this:

    class Solution:
        def findRepeatedDnaSequences(self, s):
            once, twice = set(), set()
            for i in range(len(s) - 9):
                ss = s[i:i+10]
                [once, twice][ss in once].add(ss)
            return list(twice)
    

  • 0
    Z

    How about using a counter instead of a plain dict?

        ctr = collections.Counter()
        for i in range(len(s)-9):
            ctr[s[i:i+10]]+=1
        
        return [s for s in ctr if ctr[s]>1]

  • 0

    Might as well do it like this then:

        ctr = collections.Counter(s[i:i+10] for i in range(len(s)-9))
    

  • 0
    A

    This is a pretty great solution. I want to ask if this solution or python language will have MLE problem?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.