Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,888 questions

51,815 answers

573 users

How to find the longest substring without repeating characters in Python

2 Answers

0 votes
def findLongestSubstringWithoutRepeatingCharacters(str) :
    str_size = len(str)
    start = 0
    end = 0
    start_sub = 0
    end_sub = 0
    ASCII = [0] * (256)
    
    while (end < str_size) :
        if (ASCII[ord(str[end])] > 0) :
            while (str[start] != str[end]) :
                ASCII[ord(str[start])] = 0
                start += 1
            start += 1
        else :
            ASCII[ord(str[end])] = end + 1
            if (end - start > end_sub - start_sub) :
                start_sub = start
                end_sub = end
        end += 1
        
    i = start_sub
        
    while (i <= end_sub) :
        print(str[i], end ="")
        i += 1
        
str = "xwwwqfwwxqwyq"

findLongestSubstringWithoutRepeatingCharacters(str)

 
 

'''
run:

xqwy

'''

 



answered Jul 18, 2023 by avibootz
0 votes
def longest_substring(s: str) -> str:
    start = 0
    max_length = 0
    char_index_map = {}
    longest_substr = ""

    # Iterate through the string
    for end in range(len(s)):
        if s[end] in char_index_map and char_index_map[s[end]] >= start:
            # Move the start pointer to avoid duplicates
            start = char_index_map[s[end]] + 1
        
        # Update the character's latest index
        char_index_map[s[end]] = end
        
        # Check if the current substring is the longest
        current_length = end - start + 1
        if current_length > max_length:
            max_length = current_length
            longest_substr = s[start:end + 1]
    
    return longest_substr


print(longest_substring("abcabcbb"))  # Output: "abc"
print(longest_substring("bbbbb"))    # Output: "b"
print(longest_substring("xwwwqfwwxqwyq"))   # Output: "xqwy"



'''
run:

abc
b
xqwy

'''

 



answered Apr 6, 2025 by avibootz
...