Finding longest substring in alphabetical order

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

提交回复
热议问题