Finding longest substring in alphabetical order

后端 未结 17 1516
刺人心
刺人心 2020-12-06 15:15

EDIT: I am aware that a question with similar task was already asked in SO but I\'m interested to find out the problem in this specific piece of code. I am

17条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 15:45

    Here is a single pass solution with a fast loop. It reads each character only once. Inside the loop operations are limited to

    • 1 string comparison (1 char x 1 char)
    • 1 integer increment
    • 2 integer subtractions
    • 1 integer comparison
    • 1 to 3 integer assignments
    • 1 string assignment

    No containers are used. No function calls are made. The empty string is handled without special-case code. All character codes, including chr(0), are properly handled. If there is a tie for the longest alphabetical substring, the function returns the first winning substring it encountered. Case is ignored for purposes of alphabetization, but case is preserved in the output substring.

    def longest_alphabetical_substring(string):
        start, end = 0, 0     # range of current alphabetical string
        START, END = 0, 0     # range of longest alphabetical string yet found
        prev = chr(0)         # previous character
    
        for char in string.lower():   # scan string ignoring case
            if char < prev:       # is character out of alphabetical order?
                start = end       #     if so, start a new substring 
            end += 1              # either way, increment substring length 
    
            if end - start > END - START:  # found new longest?  
                START, END = start, end    #     if so, update longest 
            prev = char                    # remember previous character
    
        return string[START : END]   # return longest alphabetical substring 
    

    Result

    >>> longest_alphabetical_substring('drurotsxjehlwfwgygygxz')
    'ehlw'
    >>> longest_alphabetical_substring('eseoojlsuai')
    'jlsu'
    >>> longest_alphabetical_substring('hixwluvyhzzzdgd')
    'luvy'
    >>>
    

提交回复
热议问题