'Finding the longest substring of string (case non-sensitive)
I need to write a case non-sensitive code that finds the longest substring of any string and returns the corresponding part of the original string without affecting the original case.
A unique substring cannot contain any repeated letters.
It should work like this: ghHcd => Hcd
My attempt is below but it is stuck in an infinite loop due to reasons which are beyond my understanding.
Edit: My goal is to achieve this without using regular expressions.
def longest_unique_substring(text):
longest_substring = ""
temp_string = ""
i = 0
while len(text) > i:
if text.lower()[i] not in temp_string.lower():
temp_string += text[i]
elif text.lower()[i] in temp_string.lower():
if temp_string > longest_substring:
longegst_substring = temp_string
temp_string = ""
i -= 1
continue
i += 1
return longest_substring
Solution 1:[1]
This modification works for me:
def longest_unique_substring(test):
longest_substring = ""
temp_string = ""
for char in test:
if char.lower() in temp_string.lower():
temp_string = temp_string[temp_string.lower().rfind(char.lower())+1:]
temp_string += char
if len(longest_substring) < len(temp_string):
longest_substring = temp_string
return longest_substring
Now longest_unique_substring('ghHcd') outputs 'Hcd'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ukulele |
