mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
0127.单词接龙 增加go语言的解法
0127.单词接龙 增加go语言的解法
This commit is contained in:
@ -158,6 +158,57 @@ class Solution:
|
||||
return 0
|
||||
```
|
||||
## Go
|
||||
```go
|
||||
func ladderLength(beginWord string, endWord string, wordList []string) int {
|
||||
wordMap, que, depth := getWordMap(wordList, beginWord), []string{beginWord}, 0
|
||||
for len(que) > 0 {
|
||||
depth++
|
||||
qLen := len(que) // 单词的长度
|
||||
for i := 0; i < qLen; i++ {
|
||||
word := que[0]
|
||||
que = que[1:] // 首位单词出队
|
||||
candidates := getCandidates(word)
|
||||
for _, candidate := range candidates {
|
||||
if _, exist := wordMap[candidate]; exist { // 用生成的结果集去查询
|
||||
if candidate == endWord {
|
||||
return depth + 1
|
||||
}
|
||||
delete(wordMap, candidate) // 删除集合中的用过的结果
|
||||
que = append(que, candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
// 获取单词Map为后续的查询增加速度
|
||||
func getWordMap(wordList []string, beginWord string) map[string]int {
|
||||
wordMap := make(map[string]int)
|
||||
for i, word := range wordList {
|
||||
if _, exist := wordMap[word]; !exist {
|
||||
if word != beginWord {
|
||||
wordMap[word] = i
|
||||
}
|
||||
}
|
||||
}
|
||||
return wordMap
|
||||
}
|
||||
|
||||
// 用26个英文字母分别替换掉各个位置的字母,生成一个结果集
|
||||
func getCandidates(word string) []string {
|
||||
var res []string
|
||||
for i := 0; i < 26; i++ {
|
||||
for j := 0; j < len(word); j++ {
|
||||
if word[j] != byte(int('a')+i) {
|
||||
res = append(res, word[:j]+string(int('a')+i)+word[j+1:])
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
## JavaScript
|
||||
```javascript
|
||||
|
Reference in New Issue
Block a user