Welcome To Golang By Example

Longest substring without repeating characters program in Go (Golang)

Table of Contents

Overview

A string is given and we have to find the longest substring in it without repeating characters. For eg if the string is

abbabcda

Then the answer would be “abcd” and the length should be 4.

We use a hash and three variables

We iterate over the string and check this hash for the current character. We simply increment the currentSubstringLength in the below two conditions

Otherwise

Let’s see a program for the same

Program

package main

import "fmt"

func main() {
	len := lengthOfLongestSubstring("abbabcda")
	fmt.Println(len)
}

func lengthOfLongestSubstring(s string) int {
	charLastIndex := make(map[rune]int)

	longestSubstringLength := 0
	currentSubstringLength := 0
	start := 0

	for index, character := range s {
		lastIndex, ok := charLastIndex[character]
		if !ok || lastIndex < index-currentSubstringLength {
			currentSubstringLength++
		} else {
			if currentSubstringLength > longestSubstringLength {
				longestSubstringLength = currentSubstringLength
			}
			start = lastIndex + 1
			currentSubstringLength = index - start + 1
		}
		charLastIndex[character] = index
	}
	if currentSubstringLength > longestSubstringLength {
		longestSubstringLength = currentSubstringLength
	}
	return longestSubstringLength
}

Output

4