Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 366a8b4

Browse filesBrowse files
authored
Merge pull request AllAlgorithms#45 from yedhink/master
Added an algorithm to find longest substring
2 parents 58002bf + 5204f2f commit 366a8b4
Copy full SHA for 366a8b4

File tree

Expand file treeCollapse file tree

1 file changed

+34
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+34
-0
lines changed

‎strings/longest_substring.py

Copy file name to clipboard
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Create an algorithm that prints the longest substring of s in which
2+
# the letters occur in alphabetical order. For example, if
3+
# s = 'azcbobobegghakl', then your program should print:
4+
# Longest substring in alphabetical order is: beggh
5+
6+
# In the case of ties, print the first substring.
7+
# For example, if s = 'abcbcd', then your program should print:
8+
# Longest substring in alphabetical order is: abc
9+
10+
11+
def longest_substr(s):
12+
count = 0
13+
maxcount = 0
14+
result = 0
15+
for char in range(len(s) - 1):
16+
if (s[char] <= s[char + 1]):
17+
count += 1
18+
if count > maxcount:
19+
maxcount = count
20+
result = char + 1
21+
else:
22+
count = 0
23+
startposition = result - maxcount
24+
return startposition, result
25+
26+
27+
# parent string
28+
s = 'azbeggaklbeggh'
29+
30+
# longest substring indexes
31+
start, end = longest_substr(s)
32+
33+
print('Longest substring in alphabetical order is:',
34+
s[start:end + 1])

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.