Longest non-repeating substring
This week is just sliding window questions. Pretty much the same as the last problem but in go and using a for loop to iterate over the second pointer. Use a hashmap to store existing non-repeating substring.
func lengthOfLongestSubstring(s string) int {
if len(s) < 2 {
return len(s)
}
word := strings.Split(s, "")
m := make(map[string]int)
max_length, curr_length, begin_index := 1, 0, 0
m[word[0]] = 0
for end_index, i := range word {
if begin_index == end_index {
continue
}
_, exists := m[i]
if exists {
begin_index = m[i] + 1
for j, k := range m {
if k < begin_index {
delete(m, j)
}
}
m[i] = end_index
// fmt.Println("begin:", begin_index, ", end:", end_index, ", m:", m)
} else {
m[i] = end_index
// fmt.Println("begin:", begin_index, ", end:", end_index, ", m:", m)
curr_length = len(m)
if curr_length > max_length {
max_length = curr_length
}
}
}
return max_length
}