- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 71 lines of Go from the credited upstream file 126B.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7)8 9func Sol126B(reader io.Reader, writer io.Writer) {10 calcMaxMatchLengths := func(pattern string) []int {11 n := len(pattern)12 maxMatchLengths := make([]int, n)13 maxLength := 014 for i := 1; i < n; i++ {15 c := pattern[i]16 for maxLength > 0 && pattern[maxLength] != c {17 maxLength = maxMatchLengths[maxLength-1]18 }19 if pattern[maxLength] == c {20 maxLength++21 }22 maxMatchLengths[i] = maxLength23 }24 return maxMatchLengths25 }26 kmpSearch := func(text, pattern string) bool {27 maxMatchLengths := calcMaxMatchLengths(pattern)28 lenP := len(pattern)29 count := 030 for i := range text {31 c := text[i]32 for count > 0 && pattern[count] != c {33 count = maxMatchLengths[count-1]34 }35 if pattern[count] == c {36 count++37 }38 if count == lenP {39 return true40 }41 }42 return false43 }44 45 in := bufio.NewReader(reader)46 out := bufio.NewWriter(writer)47 defer out.Flush()48 49 const fail = "Just a legend"50 var s string51 Fscan(in, &s)52 if len(s) < 3 {53 Fprint(out, fail)54 return55 }56 inS := s[1 : len(s)-1]57 58 lens := calcMaxMatchLengths(s)59 for maxLen := lens[len(s)-1]; maxLen > 0; maxLen = lens[maxLen-1] {60 if kmpSearch(inS, s[:maxLen]) {61 Fprint(out, s[:maxLen])62 return63 }64 }65 Fprint(out, fail)66}67 68697071