2515.到目标字符串的最短距离
链接:2515.到目标字符串的最短距离
难度:Easy
标签:数组、字符串
简介:返回到达目标字符串 target 所需的最短距离。如果 words 中不存在字符串 target ,返回 -1 。
题解 1 - cpp
- 编辑时间:2022-12-25
- 执行用时:24ms
- 内存消耗:14.1MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
int closetTarget(vector<string>& words, string target, int startIndex) {
if (words[startIndex] == target) return 0;
int i1 = startIndex, cnt1 = 0;
do {
i1 = (i1 + 1) % words.size(); cnt1++;
} while (words[i1] != target && i1 != startIndex);
if (i1 == startIndex) return -1;
int i2 = startIndex, cnt2 = 0;
do {
i2 = (i2 - 1 + words.size()) % words.size(); cnt2++;
} while (words[i2] != target && i2 != startIndex);
return min(cnt1, cnt2);
}
};