Finding longest substring in alphabetical order

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

    You can use nested for loops, slicing and sorted. If the string is not all lower-case then you can convert the sub-strings to lower-case before comparing using str.lower:

    def solve(strs):
      maxx = ''
      for i in xrange(len(strs)):
          for j in xrange(i+1, len(strs)):
              s = strs[i:j+1]
              if ''.join(sorted(s)) == s:
                  maxx = max(maxx, s, key=len)
              else:
                  break
      return maxx
    

    Output:

    >>> solve('hixwluvyhzzzdgd')
    'luvy'
    >>> solve('eseoojlsuai')
    'jlsu'
    >>> solve('drurotsxjehlwfwgygygxz')
    'ehlw'
    

提交回复
热议问题