Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AlexanderBollbach/84f5ab46ba6f8ff0e5617cd617a2e0f2 to your computer and use it in GitHub Desktop.
Save AlexanderBollbach/84f5ab46ba6f8ff0e5617cd617a2e0f2 to your computer and use it in GitHub Desktop.
func lengthOfLongestSubstring(_ s: String) -> Int {
var cache = [Character: Int]()
var tempMax = 0
var max = 0
var start = 0
for c in s.enumerated() {
// check if we've seen char before
if cache.contains(where: { $0.0 == c.element }) {
// get its index
let collisionOffset = cache[c.element]!
// if its withn the current longest string, reset the temp
if collisionOffset >= start {
tempMax -= collisionOffset - start + 1 // minus one
start = collisionOffset + 1
} else {
// else just update the last seen index
if tempMax > max { max = tempMax }
cache[c.element] = c.offset
}
}
// always increment temp
tempMax += 1
if tempMax > max { max = tempMax }
cache[c.element] = c.offset
}
return max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment