How to find the longest substring without repeating characters in Swift

1 Answer

0 votes
import Foundation

func longestSubstring(_ s: String) -> String {
    var start = 0
    var maxLength = 0
    var longestSubstr = ""
    var charIndexMap = [Character: Int]()

    for (end, char) in s.enumerated() {
        // If the character is already in the map and within the current window
        if let index = charIndexMap[char], index >= start {
            start = index + 1 // Move the start pointer to avoid duplicates
        }

        // Update the character's latest index
        charIndexMap[char] = end

        // Check if the current substring is the longest
        let currentLength = end - start + 1
        if currentLength > maxLength {
            maxLength = currentLength
            longestSubstr = String(s[s.index(s.startIndex, offsetBy: start)...s.index(s.startIndex, offsetBy: end)])
        }
    }

    return longestSubstr
}

print(longestSubstring("abcabcbb"))  // Output: "abc"
print(longestSubstring("bbbbb"))     // Output: "b"
print(longestSubstring("xwwwqfwwxqwyq")) // Output: "xqwy"



/*
run:

abc
b
xqwy

*/

 



answered Apr 7 by avibootz
...