How to check if characters in a string are alphabetically ordered

后端 未结 5 593
面向向阳花
面向向阳花 2021-01-26 08:18

I have been trying these code but there is something wrong. I simply want to know if the first string is alphabetical.

def alp(s1):
    s2=sorted(s1)
    if s2 i         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-26 08:30

    I would do it using iter to nicely get the previous element:

    def is_ordered(ss):
       ss_iterable = iter(ss)
       try:
           current_item = next(ss_iterable)
       except StopIteration:
           #replace next line to handle the empty string case as desired.
           #This is how *I* would do it, but others would prefer `return True`
           #as indicated in the comments :)
           #I suppose the question is "Is an empty sequence ordered or not?"
           raise ValueError("Undefined result.  Cannot accept empty iterable")
    
       for next_item in ss_iterable:
           if next_item < current_item:
               return False
           current_item = next_item
       return True
    

    This answer has complexity O(n) in the absolute worst case as opposed to the answers which rely on sort which is O(nlogn).

提交回复
热议问题