Finding longest substring in alphabetical order

后端 未结 17 1432
刺人心
刺人心 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:52

    Simple and easy to understand:

    s = "abcbcd"    #The original string
    
    l = len(s)    #The length of the original string
    
    maxlenstr = s[0]    #maximum length sub-string, taking the first letter of original string as value.
    
    curlenstr = s[0]    #current length sub-string, taking the first letter of original string as value.
    
    for i in range(1,l):    #in range, the l is not counted. 
    
        if s[i] >= s[i-1]:    #If current letter is greater or equal to previous letter,
            curlenstr += s[i] #add the current letter to current length sub-string
        else:        
            curlenstr = s[i]  #otherwise, take the current letter as current length sub-string
    
        if len(curlenstr) > len(maxlenstr): #if current cub-string's length is greater than max one,
                maxlenstr = curlenstr;      #take current one as max one.
    
    print("Longest substring in alphabetical order is:", maxlenstr)
    
    0 讨论(0)
  • 2020-12-06 15:54

    I agree with @Abhijit about the power of itertools.groupby() but I took a simpler approach to (ab)using it and avoided the boundary case problems:

    from itertools import groupby
    
    LENGTH, LETTERS = 0, 1
    
    def longest_sorted(string):
        longest_length, longest_letters = 0, []
        key, previous_letter = 0, chr(0)
    
        def keyfunc(letter):
            nonlocal key, previous_letter
            if letter < previous_letter:
                key += 1
    
            previous_letter = letter
            return key
    
        for _, group in groupby(string, keyfunc):
            letters = list(group)
            length = len(letters)
    
            if length > longest_length:
                longest_length, longest_letters = length, letters
    
        return ''.join(longest_letters)
    
    print(longest_sorted('hixwluvyhzzzdgd'))
    print(longest_sorted('eseoojlsuai'))
    print(longest_sorted('drurotsxjehlwfwgygygxz'))
    print(longest_sorted('abcdefghijklmnopqrstuvwxyz'))
    

    OUTPUT

    > python3 test.py
    luvy
    jlsu
    ehlw
    abcdefghijklmnopqrstuvwxyz
    >
    
    0 讨论(0)
  • 2020-12-06 15:55

    Here. This does what you want. One pass, no need for recursion.

    def find_longest_substring_in_alphabetical_order(s):
        groups = []
        cur_longest = ''
        prev_char = ''
        for c in s.lower():
            if prev_char and c < prev_char:
                groups.append(cur_longest)
                cur_longest = c
            else:
                cur_longest += c
            prev_char = c
        return max(groups, key=len) if groups else s
    

    Using it:

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

    Note: It will probably break on strange characters, has only been tested with the inputs you suggested. Since this is a "homework" question, I will leave you with the solution as is, though there is still some optimization to be done, I wanted to leave it a little bit understandable.

    0 讨论(0)
  • 2020-12-06 15:55

    Assuming this is from Edx course: till this question, we haven't taught anything about strings and their advanced operations in python So, I would simply go through the looping and conditional statements

    string =""             #taking a plain string to represent the then generated string
    present =""             #the present/current longest string
    for i in range(len(s)): #not len(s)-1 because that totally skips last value
        j = i+1            
        if j>= len(s):    
            j=i           #using s[i+1] simply throws an error of not having index
        if s[i] <= s[j]:  #comparing the now and next value
            string += s[i] #concatinating string if above condition is satisied
        elif len(string) != 0 and s[i] > s[j]: #don't want to lose the last value
            string += s[i] #now since s[i] > s[j] #last one will be printed
            if len(string) > len(present): #1 > 0 so from there we get to store many values
                present = string #swapping to largest string
            string = ""
        if len(string) > len(present): #to swap from if statement
            present = string
    if present == s[len(s)-1]: #if no alphabet is in order then first one is to be the output
        present = s[0]
    print('Longest substring in alphabetical order is:' + present)
    
    0 讨论(0)
  • 2020-12-06 16:04
    s = 'gkuencgybsbezzilbfg'
    x = s.lower()
    y = ''
    z = [] #creating an empty listing which will get filled
    
    for i in range(0,len(x)):
        if i == len(x)-1:
           y = y + str(x[i])
           z.append(y)
           break 
        a = x[i] <= x[i+1]
        if a == True:
            y = y + str(x[i])
        else: 
            y = y + str(x[i])
            z.append(y)  # fill the list 
            y = ''
    # search of 1st longest string        
    L = len(max(z,key=len))      # key=len takes length in consideration 
    for i in range(0,len(z)):
        a = len(z[i])
        if a == L:   
            print 'Longest substring in alphabetical order is:' + str(z[i])
            break
    
    0 讨论(0)
提交回复
热议问题