From dbecfb3b6bf85b652e7423db67784e3f1d3ed4ef Mon Sep 17 00:00:00 2001 From: = <--gbloal> Date: Wed, 5 Jun 2024 18:10:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=8D=E8=BD=AC=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E5=89=8D=E7=BC=80(2000)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- leetcode/简单/反转单词前缀.js | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 leetcode/简单/反转单词前缀.js diff --git a/leetcode/简单/反转单词前缀.js b/leetcode/简单/反转单词前缀.js new file mode 100644 index 0000000..a51cd6f --- /dev/null +++ b/leetcode/简单/反转单词前缀.js @@ -0,0 +1,41 @@ +/* +2000. 反转单词前缀 +简单 + +相关标签 +相关企业 + +提示 +给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i ,反转 word 中 +从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。 + +例如,如果 word = "abcdefd" 且 ch = "d" ,那么你应该 反转 从下标 0 开始、直到下标 3 结束(含下标 3 )。结果字符串将会是 "dcbaefd" 。 +返回 结果字符串 。 +*/ + +/* +思路:先找到字符出现的位置,之后设置两个瓜下表交换首尾字符即可 +*/ + +/** + * @param {string} word + * @param {character} ch + * @return {string} + */ +const reversePrefix = function (word, ch) { + const index = word.indexOf(ch); + if (index < 0) return word; + let left = 0; + let right = index; + const arr = [...word]; + while (left < right) { + const tmp = arr[left]; + arr[left] = arr[right]; + arr[right] = tmp; + left++; + right--; + } + return arr.join(''); +}; + +console.log(reversePrefix('abcdefd', 'd'));