"Longest Duplicate Substring" hard task No 1044 not accepted improved bruteforce solution

This commit is contained in:
2022-04-21 20:33:55 +03:00
parent f4a90a3f21
commit 7de2ef26ff
2 changed files with 45 additions and 2 deletions

View File

@@ -52,6 +52,47 @@ func LongestDupSubstringReversedBruteforce(s string) string {
return ""
}
func LongestDupSubstring(s string) string {
return LongestDupSubstringBruteforce(s)
func LongestDupSubstringSmartforce(s string) string {
strLen := len(s)
if strLen < 2 {
return ""
}
indicesCurrent := []int{}
indicesNext := []int{}
res := ""
for i := 0; i < strLen; i++ {
for j := 0; j < strLen; j++ {
indicesCurrent = append(indicesCurrent, j)
}
for ln := 1; ln <= strLen-i; ln++ {
word1 := s[i : i+ln]
for _, index := range indicesCurrent {
if index+ln > strLen {
continue
}
word2 := s[index : index+ln]
if (word1 == word2) && (index != i) {
if len(res) < len(word1) {
res = word1
}
indicesNext = append(indicesNext, index)
}
}
indicesCurrent = indicesNext
indicesNext = []int{}
}
}
return res
}
func LongestDupSubstring(s string) string {
return LongestDupSubstringSmartforce(s)
}