Concise O(n) 6-liner in Python


  • 4
    O

    Record the longest length for the substrings that end with each letter.

    Use 'abcdefghijklmnopqrstuvwxyza’ to check if two letters are near each other.

    class Solution(object):
        def findSubstringInWraproundString(self, p):
            p, d, lo = '0'+p, collections.defaultdict(int), 0
            for hi in range(1, len(p)):
                if p[hi-1]+p[hi] not in 'abcdefghijklmnopqrstuvwxyza':
                    lo = hi
                d[p[hi]] = max(d[p[hi]], hi+1-lo)
            return sum(d.values())
    

  • 0
    S

    thx!!! nice solution!


Log in to reply
 

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