Skip to Main Content
Blog

Get Longest Substring in Python

Get Longest Substring in Python

def main():
	"""
	Prints the longest substring of same characters in a string.
	"""

	text = input("Enter string: ")
	result = longest(text)
	print(result)


def longest(txt: str):
	"""
	Finds the longest substring of same characters in a string.
	"""

	beg = -1
	end = -1

	# Iterate through all the characters in the string
	for i in range(len(txt)):
		a = txt[i]
		j = i + 1

		# Find the end of the substring with the same character
		for j in range(j, len(txt) + 1):
			b = txt[j]
			if a != b:
				break

		# Update the pointers if the current substring is longer
		if j - i > end - beg:
			beg = i
			end = j

	# If there are no same characters, return an empty string
	if end - beg == 1:
		return ""

	# Return the longest substring
	return txt[beg:end]


if __name__ == "__main__":
	main()