Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to check whether a string can be segmented into a sequence of words from a dictionary in Go

2 Answers

0 votes
package main

import (
    "fmt"
)

func wordBreak(s string, dict map[string]bool) bool {
    slen := len(s)
    result := make([]bool, slen+1)
    result[0] = true // empty string is always segmentable

    for i := 1; i <= slen; i++ {
        for j := 0; j < i; j++ {
            if result[j] && dict[s[j:i]] {
                result[i] = true
                break
            }
        }
    }

    return result[slen]
}

func main() {
    dict := map[string]bool{
        "future":  true,
        "depends": true,
        "the":     true,
        "on":      true,
        "your":    true,
        "dreams":  true,
        "start":   true,
        "today":   true,
    }

    s := "futuredependsonyourdreams"

    if wordBreak(s, dict) {
        fmt.Println("The string can be segmented")
    } else {
        fmt.Println("The string cannot be segmented")
    }
}



/*
run:

The string can be segmented

*/

 



answered Sep 29, 2025 by avibootz
0 votes
package main

import (
    "fmt"
)

func isInDict(word string, dict []string) bool {
    for _, w := range dict {
        if w == word {
            return true
        }
    }
    
    return false
}

func wordBreak(str string, result string, dict []string) {
    strsize := len(str)
    for i := 1; i <= strsize; i++ {
        subStr := str[:i]

        if isInDict(subStr, dict) {
            if i == strsize {
                result += subStr
                fmt.Println(result)
                return
            }
            wordBreak(str[i:], result+subStr+" ", dict)
        }
    }
}

func main() {
    str := "butterflyplaybasketballwithbags"
    dict := []string{
        "butterfly", "basketball", "bagpiper", "and", "play",
        "with", "butter", "fly", "basket", "ball", "bags",
    }

    wordBreak(str, "", dict)
}



/*
run:

butter fly play basket ball with bags
butter fly play basketball with bags
butterfly play basket ball with bags
butterfly play basketball with bags

*/

 



answered Sep 29, 2025 by avibootz
...