**题目:**
> 给出字符串dogandcat及字典{"do", "d", "gand", "g", "and", "dog", "cat", "c", "at", "in", "play", "i", "nplay"},
> 找出组成字符串的所以可能的单词组合。
之前用haskell写过一个实现,但接触golang之后,发现可以写成更简明的版本,代码如下:
```
package main
import (
"fmt"
)
var word = "dogandcat"
var dicts = []string{"do", "d", "gand", "g", "and", "dog", "cat", "c", "at", "in", "play", "i", "nplay"}
var results = [][]string{}
var cpyCounter = 0
var stepCounter = 0
func IsContainsInDicts(str string) bool {
for _, v := range dicts {
if v == str {
return true
}
}
return false
}
func breaker(matched []string, pos int) {
if pos >= len(word) {
results = append(results, matched)
return
}
match := []byte{}
for i := pos; i < len(word); i++ {
match = append(match, word[i])
aword := string(match)
stepCounter += 1
if IsContainsInDicts(aword) {
cpyMatched := make([]string, len(matched))
copy(cpyMatched, matched)
cpyMatched = append(cpyMatched, aword)
cpyCounter += 1
breaker(cpyMatched, i+1)
}
}
}
func main() {
fmt.Println(word)
fmt.Println(dicts)
breaker([]string{}, 0)
fmt.Println()
fmt.Println(results)
fmt.Println()
fmt.Println("step times: ", stepCounter)
fmt.Println("cpy times: ", cpyCounter)
}
```
以上代码还有点性能上的小问题:
- 1)如果字典很大,IsContainsInDicts的效率就很低;
- 2)如果字符串很大,result很耗内存;
如果有更好的方法,欢迎指教,谢谢!
有疑问加站长微信联系(非本文作者))