How to find the longest repeating substring in a string with Go

1 Answer

0 votes
package main

import (
	"fmt"
)

// Function to find the longest common prefix between two strings
func longestCommonPrefix(sub1, sub2 string) string {
	min := len(sub1)
	if len(sub2) < min {
		min = len(sub2)
	}

	for i := 0; i < min; i++ {
		if sub1[i] != sub2[i] {
			return sub1[:i]
		}
	}
	
	return sub1[:min]
}

// Function to find the longest repeating substring
func longestRepeatingSubstring(s string) string {
	lrs := ""
	size := len(s)

	for i := 0; i < size; i++ {
		for j := i + 1; j < size; j++ {
			lcp := longestCommonPrefix(s[i:], s[j:])
			if len(lcp) > len(lrs) {
				lrs = lcp
			}
		}
	}

	return lrs
}

func main() {
	s := "javascriptpythonphpjavacdartcppjavacsharpgo"

	fmt.Println(longestRepeatingSubstring(s))
}


/*
run:

pjavac

*/

 



answered Sep 22, 2025 by avibootz
...