LeetCode Problem: Longest Subtring Without Repeating Characters
Problem statement:
Given a string (s), find the length of the longest substring without repeating characters
Example:
Input:
"abcabcbb"
Expected output:
3
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Golang Solution:
func lengthOfLongestSubstring(s string) int {
if len(s) == 0 {
return 0
}
if len(s) == 1 {
return 1
}
maxLen := 0
i := 0
indexMap := make(map[byte]int, 0)
tempLen := 0
for j := 0; j < len(s); j++ {
if res, ok := indexMap[s[j]]; ok {
i = res + 1
indexMap = make(map[byte]int, 0)
j = i - 1
tempLen = 0
} else {
tempLen += 1
indexMap[s[j]] = j
if tempLen > maxLen {
maxLen = tempLen
}
}
}
return maxLen
}