How to find the longest common prefix of all the words in a string with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "regexp"
    "strings"
)

func LongestCommonPrefix(input string) string {
    input = strings.TrimSpace(input)
    if input == "" {
        return ""
    }

    // Split by non‑word characters (same as Java's split("\\W+"))
    re := regexp.MustCompile(`\W+`)
    words := re.Split(strings.ToLower(input), -1)

    // Filter out empty tokens
    filtered := make([]string, 0, len(words))
    for _, w := range words {
        if w != "" {
            filtered = append(filtered, w)
        }
    }

    if len(filtered) == 0 {
        return ""
    }

    prefix := filtered[0]

    for _, w := range filtered {
        for !strings.HasPrefix(w, prefix) {
            if len(prefix) == 0 {
                return ""
            }
            prefix = prefix[:len(prefix)-1]
        }
    }

    return prefix
}

func main() {
    s1 := "The lowly inhabitants of the lowland were surprised to see the lower branches."
    fmt.Printf("LCP: '%s'\n", LongestCommonPrefix(s1))

    s2 := "unclear, uncertain, unexpected"
    fmt.Printf("LCP: '%s'\n", LongestCommonPrefix(s2))
}



/*
run:

LCP: ''
LCP: 'un'

*/

 



answered Mar 12 by avibootz

Related questions

...