forked from AllAlgorithms/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_substring.py
More file actions
34 lines (27 loc) · 953 Bytes
/
Copy pathlongest_substring.py
File metadata and controls
34 lines (27 loc) · 953 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Create an algorithm that prints the longest substring of s in which
# the letters occur in alphabetical order. For example, if
# s = 'azcbobobegghakl', then your program should print:
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring.
# For example, if s = 'abcbcd', then your program should print:
# Longest substring in alphabetical order is: abc
def longest_substr(s):
count = 0
maxcount = 0
result = 0
for char in range(len(s) - 1):
if (s[char] <= s[char + 1]):
count += 1
if count > maxcount:
maxcount = count
result = char + 1
else:
count = 0
startposition = result - maxcount
return startposition, result
# parent string
s = 'azbeggaklbeggh'
# longest substring indexes
start, end = longest_substr(s)
print('Longest substring in alphabetical order is:',
s[start:end + 1])