场景:一个字符串'abcdef' 现在词典'abc' 'ef',判断这个字符串是否可以分词
无耻的用一下语言的map,也算是实现了
package mainimport ( "fmt")var words = []string{"abc", "df", "wg", "aa"}var dict = make(map[string]bool)func init() { for _, word := range words { dict[word] = true }}func parse_words(words string) bool { var words_len = len(words) if words_len < 1 { _, ok := dict[words] return ok } var flag = false for i := 1; i <= words_len; i++ { first_string := words[:i] if _, ok := dict[first_string]; ok { if i != words_len { flag = parse_words(words[i:]) } else { return true } } else { continue } } return flag}func main() { can_parse := parse_words("abcaad") fmt.Println(can_parse) can_parse = parse_words("abcaa") fmt.Println(can_parse)}
输出结果:
falsetrue
后续:自己有空实现一下类似的map功能