2515.到目标字符串的最短距离:从中间往两边遍历
【LetMeFly】2515.到目标字符串的最短距离:从中间往两边遍历
力扣题目链接:https://leetcode.cn/problems/shortest-distance-to-target-string-in-a-circular-array/
给你一个下标从 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 个单位,到达下标 2 。 - 向左移动 1 个单位,到达下标 2 。 到达 "leetcode" 的最短距离是 1 。
示例 3:
输入:words = ["i","eat","leetcode"], target = "ate", startIndex = 0 输出:-1 解释:因为 words 中不存在字符串 "ate" ,所以返回 -1 。
提示:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]和target仅由小写英文字母组成0 <= startIndex < words.length
解题方法:遍历
从startIndex开始往两边遍历,每个方向最多走$\lfloor\frac{len(words)}{2}+1\rfloor$步。
遇到target则立刻返回,最终都没有遇到则返回-1。
- 时间复杂度$O(len(words)\times len(target))$
- 空间复杂度$O(1)$
AC代码
C++
1 | |
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源
2515.到目标字符串的最短距离:从中间往两边遍历
https://blog.letmefly.xyz/2026/04/15/LeetCode 2515.到目标字符串的最短距离/