From f01233e23ba0c296e8df959dc5a6b8f23ec2727d Mon Sep 17 00:00:00 2001 From: wang2jun <91008685+wang2jun@users.noreply.github.com> Date: Thu, 8 Dec 2022 13:52:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20127=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E6=8E=A5=E9=BE=99=20TypeScript=20=E7=89=88=E6=9C=AC=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 127单词接龙 TypeScript 版本代码 --- problems/0127.单词接龙.md | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index 2e30123d..bc21d0ad 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -247,6 +247,55 @@ var ladderLength = function(beginWord, endWord, wordList) { }; ``` +## TypeScript +```typescript +function ladderLength( + beginWord: string, + endWord: string, + wordList: string[] +): number { + const words = new Set(wordList); + if (!words.has(endWord)) return 0; + if (beginWord.length === 1) return 2; + let current = new Set([beginWord]); + let rightcurrent = new Set([endWord]); + words.delete(endWord); + let step = 1; + while (current.size) { + if (current.size > rightcurrent.size) { + [current, rightcurrent] = [rightcurrent, current]; + } + const temp: Set = new Set(); + for (const word of current) { + for (const right of rightcurrent) { + if (diffonechar(word, right)) { + return step + 1; + } + } + for (const other of words) { + if (diffonechar(other, word)) { + temp.add(other); + + words.delete(other); + } + } + } + if (temp.size === 0) return 0; + current = temp; + step = step + 1; + } + return 0; +} + +function diffonechar(word1: string, word2: string): boolean { + let changes = 0; + for (let i = 0; i < word1.length; i++) { + if (word1[i] != word2[i]) changes += 1; + } + return changes === 1; +} +``` +