Find the longest substring in alphabetical order

前端 未结 17 2478
有刺的猬
有刺的猬 2020-11-30 09:12

I have this code that I found on another topic, but it sorts the substring by contiguous characters and not by alphabetical order. How do I correct it for alphabetical order

17条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 09:42

    In a recursive way, you can import count from itertools

    Or define a same method:

    def loops( I=0, S=1 ):
        n = I
        while True:
            yield n
            n += S
    

    With this method, you can obtain the value of an endpoint, when you create any substring in your anallitic process.

    Now looks the anallize method (based on spacegame issue and Mr. Tim Petters suggestion)

    def anallize(inStr):
        # empty slice (maxStr) to implement
        # str native methods
        # in the anallize search execution
        maxStr = inStr[0:0]
        # loop to read the input string (inStr)
        for i in range(len(inStr)):
            # loop to sort and compare each new substring
            # the loop uses the loops method of past
            # I = sum of: 
            #     (i) current read index
            #     (len(maxStr)) current answer length
            #     and 1
            for o in loops(i + len(maxStr) + 1):
                # create a new substring (newStr)
                # the substring is taked:
                # from: index of read loop (i)
                # to:   index of sort and compare loop (o)
                newStr = inStr[i:o]
    
                if len(newStr) != (o - i):# detect and found duplicates
                    break
                if sorted(newStr) == list(newStr):# compares if sorted string is equal to listed string
                    # if success, the substring of sort and compare is assigned as answer
                    maxStr = newStr
        # return the string recovered as longest substring
        return maxStr
    

    Finally, for test or execution pourposes:

    # for execution pourposes of the exercise:
    s = "azcbobobegghakl"
    print "Longest substring in alphabetical order is: " + anallize( s )
    

    The great piece of this job started by: spacegame and attended by Mr. Tim Petters, is in the use of the native str methods and the reusability of the code.

    The answer is:

    Longest substring in alphabetical order is: ccl

提交回复
热议问题