Find the longest substring in alphabetical order

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

    input_str = "cyqfjhcclkbxpbojgkar"
    length = len(input_str) # length of the input string
    iter = 0
    result_str = '' # contains latest processed sub string
    longest = '' # contains longest sub string alphabetic order 
    while length > 1: # loop till all char processed from string
        count = 1
        key = input_str[iter] #set last checked char as key 
        result_str += key # start of the new sub string
        for i in range(iter+1, len(input_str)): # discard processed char to set new range
          length -= 1
          if(key <= input_str[i]): # check the char is in alphabetic order 
            key = input_str[i]
            result_str += key # concatenate the char to result_str
            count += 1
          else:
            if(len(longest) < len(result_str)): # check result and longest str length
              longest = result_str # if yes set longest to result
            result_str = '' # re initiate result_str for new sub string
            iter += count # update iter value to point the index of last processed char
            break
    
        if length is 1: # check for the last iteration of while loop
            if(len(longest) < len(result_str)):
              longest = result_str
    
    print(longest);
    

提交回复
热议问题