Find the longest substring in alphabetical order

前端 未结 17 2474
有刺的猬
有刺的猬 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:58

    In Python character comparison is easy compared to java script where the ASCII values have to be compared. According to python

    a>b gives a Boolean False and b>a gives a Boolean True

    Using this the longest sub string in alphabetical order can be found by using the following algorithm :

    def comp(a,b):
        if a<=b:
            return True
        else:
            return False
    s = raw_input("Enter the required sting: ")
    final = []
    nIndex = 0
    temp = []
    for i in range(nIndex, len(s)-1):
        res = comp(s[i], s[i+1])
        if res == True:       
               if temp == []:
               #print i
                   temp.append(s[i])
                   temp.append(s[i+1])
               else:
                   temp.append(s[i+1])
           final.append(temp)
            else:
           if temp == []:
            #print i
            temp.append(s[i])
           final.append(temp)
           temp = []
    lengths = []
    for el in final:
        lengths.append(len(el))
    print lengths
    print final
    lngStr = ''.join(final[lengths.index(max(lengths))])
    print "Longest substring in alphabetical order is: " + lngStr
    

提交回复
热议问题