Created
August 29, 2018 17:02
-
-
Save AlexanderBollbach/84f5ab46ba6f8ff0e5617cd617a2e0f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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