python - Find the longest substring with contiguous characters, where the string may be jumbled -


given string, find longest substring characters contiguous (i.e. consecutive letters) possibly jumbled (i.e. out of order). example:
input : "owadcbjkl"
output: "adcb"
consider adcb contiguous forms abcd.

(this interview question.)

i have idea of running while loop 2 conditions, 1 checks continuous characters using python's ord , condition find minimum , maximum , check if following characters fall in range.

is there way problem solved low running time complexity? best can achieve o(n^2) n length of input string , ord() seems slow operation.

if substring defined ''.join(sorted(substr)) in alphabet then:

  • there no duplicates in substring , therefore size of longest substring less (or equal to) size of alphabet

  • (ord(max(substr)) - ord(min(substr)) + 1) == len(substr), ord() returns position in alphabet (+/- constant) (builtin ord() can used lowercase ascii letters)

here's o(n*m*m)-time, o(m)-space solution, n len(input_string) , m len(alphabet):

from itertools import count  def longest_substr(input_string):     maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)     start in range(len(input_string)): # o(n)         end in count(start + len(maxsubstr) + 1): # o(m)             substr = input_string[start:end] # o(m)             if len(set(substr)) != (end - start): # found duplicates or eos                 break             if (ord(max(substr)) - ord(min(substr)) + 1) == len(substr):                 maxsubstr = substr     return maxsubstr 

example:

print(longest_substr("owadcbjkl")) # -> adcb 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -