How to merge two strings based on shared suffix and prefix in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func mergeOnOverlap(a, b string) string {
    lenA := len(a)
    lenB := len(b)

    maxPossibleOverlapLen := lenA
    if lenB < maxPossibleOverlapLen {
        maxPossibleOverlapLen = lenB
    }

    overlap := 0

    for l := maxPossibleOverlapLen; l > 0; l-- {
        if a[lenA-l:] == b[:l] {
            overlap = l
            break
        }
    }

    return a + b[overlap:]
}

func main() {
    a := "fantasy time travel technology"
    b := "technology extraterrestrial life"

    fmt.Println(mergeOnOverlap(a, b))
}

 
 
/*
run:
 
fantasy time travel technology extraterrestrial life
 
*/

 



answered Jan 24 by avibootz
...