LeetCode 2515. 到目标字符串的最短距离 C#
原题链接
简单
作者:
hpstory
,
2023-01-03 14:50:42
,
所有人可见
,
阅读 88
C# 一次遍历代码
public class Solution {
public int ClosetTarget(string[] words, string target, int startIndex) {
int n = words.Length;
int result = n;
for (int i = 0; i < n; i++){
if (words[i] == target){
result = Math.Min(result, Math.Min(Math.Abs(i - startIndex), n - Math.Abs(i - startIndex)));
}
}
if (result == n) return -1;
return result;
}
}
C# 二次遍历代码
public class Solution {
public int ClosetTarget(string[] words, string target, int startIndex) {
int n = words.Length;
int left = 0, right = 0;
for (int i = startIndex; ;i = (i + 1) % n){
if (words[i] == target) break;
left++;
if (left > n) return -1;
}
for (int i = startIndex; ;i = (i - 1 + n) % n){
if (words[i] == target) break;
right++;
}
return Math.Min(left, right);
}
}