From b7c8081053e9e87a26c50ebe10b0d1b1427676d6 Mon Sep 17 00:00:00 2001 From: Rostislav Kuratch Date: Thu, 16 Jun 2022 23:08:56 +0300 Subject: [PATCH] "3. Longest Substring Without Repeating Characters" drastically optimised accepted solution --- 3-longest-substr-no-repeat-chars.go | 33 +++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/3-longest-substr-no-repeat-chars.go b/3-longest-substr-no-repeat-chars.go index aaf6b82..e33351a 100644 --- a/3-longest-substr-no-repeat-chars.go +++ b/3-longest-substr-no-repeat-chars.go @@ -86,6 +86,35 @@ func lengthOfLongestSubstringSlidingWindow(s string) int { return maxChars } -func LengthOfLongestSubstring(s string) int { - return lengthOfLongestSubstringSlidingWindow(s) +func lengthOfLongestSubstringExpandingWindow(s string) int { + maxChars := 0 + + if len(s) == 0 { + return 0 + } + + for i := 0; i < len(s)-maxChars; i++ { + charMap := [255]int{} + charMapSize := 0 + + for j := i; j < len(s); j++ { + charMap[s[j]]++ + if charMap[s[j]] > 1 { + break + } else { + charMapSize++ + } + + } + + if maxChars < charMapSize { + maxChars = charMapSize + } + } + + return maxChars +} + +func LengthOfLongestSubstring(s string) int { + return lengthOfLongestSubstringExpandingWindow(s) }