Finding longest substring in alphabetical order

后端 未结 17 1491
刺人心
刺人心 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)
    

提交回复
热议问题