「每日LeetCode」2023年2月3日

本文最后更新于:2023年3月19日 晚上

2515.到目标字符串的最短距离

2515.到目标字符串的最短距离

Category Difficulty Likes Dislikes
algorithms Easy (55.58%) 6 -

Tags
Companies
给你一个下标从 0 开始的 环形 字符串数组 words 和一个字符串 target 。环形数组 意味着数组首尾相连。

  • 形式上, words[i] 的下一个元素是 words[(i + 1) % n] ,而 words[i] 的前一个元素是 words[(i - 1 + n) % n] ,其中 n 是 words 的长度。

从 startIndex 开始,你一次可以用 1 步移动到下一个或者前一个单词。
返回到达目标字符串 target 所需的最短距离。如果 words 中不存在字符串 target ,返回 -1 。

示例 1:
输入:words = [“hello”,”i”,”am”,”leetcode”,”hello”], target = “hello”, startIndex = 1 输出:1 解释:从下标 1 开始,可以经由以下步骤到达 “hello” : - 向右移动 3 个单位,到达下标 4 。 - 向左移动 2 个单位,到达下标 4 。 - 向右移动 4 个单位,到达下标 0 。 - 向左移动 1 个单位,到达下标 0 。 到达 “hello” 的最短距离是 1 。
示例 2:
输入:words = [“a”,”b”,”leetcode”], target = “leetcode”, startIndex = 0 输出:1 解释:从下标 0 开始,可以经由以下步骤到达 “leetcode” : - 向右移动 2 个单位,到达下标 3 。 - 向左移动 1 个单位,到达下标 3 。 到达 “leetcode” 的最短距离是 1 。
示例 3:
输入:words = [“i”,”eat”,”leetcode”], target = “ate”, startIndex = 0 输出:-1 解释:因为 words 中不存在字符串 “ate” ,所以返回 -1 。

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] 和 target 仅由小写英文字母组成
  • 0 <= startIndex < words.length

Discussion | Solution

思路

按题意模拟即可

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
* @lc app=leetcode.cn id=2515 lang=javascript
*
* [2515] 到目标字符串的最短距离
*/

// @lc code=start
/**
* @param {string[]} words
* @param {string} target
* @param {number} startIndex
* @return {number}
*/
var closetTarget = function (words, target, startIndex) {
let min = Infinity;
const indexArr = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
if (word === target) indexArr.push(i);
}
for (const targetIndex of indexArr) {
const len1 = Math.abs(startIndex - targetIndex);
const len2 = words.length - Math.abs(-startIndex + targetIndex);
min = Math.min(min, len1, len2);
}

return min === Infinity ? -1 : min;
};
// @lc code=end