Hy friends, today i am showing you how to get longest substring in a string by alphabetical order. Now first we need to know what is longest substring.
Suppose i give you a string abcacd.
Now the longest substring in the string is abc , because it take a sequential order of character.
Now how do we think it ? First we can think the algorithm i like that
if index 0 character ASCII value is less then index 1 character then we accept the character of index 0. Same case with index 1 with index 2. Now when the sequence break ?
If index 2 value is greater then index 3 value then the sequence in break, so the substring is index 0 to index 2.
But i python you know you can do what you want like a superhero :p .
Pythonic way is different thinking. Here you can compare two character without compering ASCII code. I try to write the code simple as far as i can.
si = ['azcbobobegghakl', 'abcdefghijklmnopqrstuvwxyz', 'nqlkcvjkwytg', 'bovgfeiromsncq'] for s in si: max_subStr = '' for i in range(len(s)): sub_string = s[i] char_count = 0 while i + 1 < len(s) and s[i]<=s[i+1]: char_count+=1 i+=1 sub_string+=s[i] if len(sub_string)> len(max_subStr): max_subStr = sub_string print(max_subStr)
0 Comments