From 06d15bb5917f61112388154b6db63e55e9f647f2 Mon Sep 17 00:00:00 2001 From: wangya <1264178545@qq.com> Date: Tue, 13 Aug 2024 09:14:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=8D=A1=E7=A0=81?= =?UTF-8?q?=E7=BD=910110.=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=8E=A5=E9=BE=99=20J?= =?UTF-8?q?S=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0110.字符串接龙.md | 76 +++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/problems/kamacoder/0110.字符串接龙.md b/problems/kamacoder/0110.字符串接龙.md index feeec6dd..b96290b6 100644 --- a/problems/kamacoder/0110.字符串接龙.md +++ b/problems/kamacoder/0110.字符串接龙.md @@ -38,7 +38,7 @@ ebc dec dfc yhn -``` +``` 输出示例 @@ -224,6 +224,80 @@ public class Main { ### Javascript +```javascript +const r1 = require('readline').createInterface({ input: process.stdin }); +// 创建readline接口 +let iter = r1[Symbol.asyncIterator](); +// 创建异步迭代器 +const readline = async () => (await iter.next()).value; + +let N //输入字符串个数 +let beginStr //开始字符串 +let endStr //结束字符串 +let strSet = new Set() //字符串集合 +let visitedMap = new Map() //访问过的字符串 + +// 读取输入,初始化地图 +const init = async () => { + let line = await readline(); + line = line.trim() + N = Number(line); + + line = await readline(); + line = line.trim().split(' ') + beginStr = line[0] + endStr = line[1] + + for (let i = 0; i < N; i++) { + line = await readline() + line = line.trim() + strSet.add(line.trim()) + } +} + +(async function () { + + // 读取输入,初始化数据 + await init() + + // 初始化队列 + let queue = [] + queue.push(beginStr) + + // 初始化visitMap + visitedMap.set(beginStr, 1) + + while (queue.length) { + let word = queue.shift() + let path = visitedMap.get(word) + + // 遍历26个字母 + for (let i = 0; i < word.length; i++) { + let newWord = word.split('') // 用一个新字符串替换str,因为每次要置换一个字符 + for (let j = 0; j < 26; j++) { + newWord[i] = String.fromCharCode('a'.charCodeAt() + j) + // 发现替换字母后,字符串与终点字符串相同 + if (newWord.join('') === endStr) { + console.log(path + 1); + return 0; // 找到了路径 + } + + // 字符串集合里出现了newWord,并且newWord没有被访问过 + if (strSet.has(newWord.join('')) && !visitedMap.has(newWord.join(''))) { + // 添加访问信息,并将新字符串放到队列中 + queue.push(newWord.join('')) + visitedMap.set(newWord.join(''), path + 1) + } + } + } + } + + console.log(0); +})() +``` + + + ### TypeScript ### PhP