Created
October 1, 2022 15:34
-
-
Save sagar290/15db24852444849d52e650d9f1265e7c to your computer and use it in GitHub Desktop.
Length of Longest Substring
This file contains 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
// solution 1 | |
func lengthOfLongestSubstring(s string) int { | |
length := len(s) | |
var result []string | |
// fmt.Println(s[1:4]) | |
for i := 0; i < length; i++ { | |
for j := 0; j < length+1; j++ { | |
if j < i { | |
continue | |
} | |
if strings.Contains(s, s[i:j]) { | |
if checkDuplicate(s[i:j]) { | |
result = append(result, s[i:j]) | |
} | |
} | |
} | |
} | |
max := func(a []string) (max int) { | |
if len(a) == 0 { | |
return 0 | |
} | |
max = len(a[0]) | |
for _, value := range a { | |
if len(value) > max { | |
max = len(value) | |
} | |
} | |
return max | |
}(result) | |
return max | |
} | |
// solution 2 | |
func lengthOfLongestSubstring(s string) int { | |
length := len(s) | |
result := map[string]int{} | |
var left, right int | |
var count int = 0 | |
for right < length { | |
result[string(s[right])] += 1 | |
for result[string(s[right])] > 1 { | |
result[string(s[left])] -= 1 | |
left++ | |
} | |
if count < right-left+1 { | |
count = right - left + 1 | |
} | |
right++ | |
} | |
return count | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment