- Difficulty: Easy
Problem
Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Input: S = "loveleetcode", C = ‘e‘
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:
S
string length is in[1, 10000]
.C
is a single character, and guaranteed to be in stringS
.- All letters in
S
andC
are lowercase.
Solution
找到 S
中第一个 C
的位置,然后从这里往两边扩展距离,然后找到下一个 C
的位置,以此类推,直到遍历完 S
中所有的 C
。
实际上不难看出,位于 C
左边的字符,其距离计算只需进行一次(任意一个字符到 C
的距离,肯定比它到下一个 C
的距离更短),故向左扩展距离的时候就没必要扩展到字符串开头的位置。
public class Solution
{
public int[] ShortestToChar(string S, char C)
{
int[] ret = new int[S.Length];
int left = 0, right = S.Length, distance;
int startIndex = S.IndexOf(C, left);
Array.Fill(ret, 65535);
while(startIndex != -1)
{
distance = 0;
for(int i = startIndex; i >= left; i--)
{
if (ret[i] >= distance)
ret[i] = distance;
distance++;
}
distance = 0;
for(int i = startIndex; i < right; i++)
{
if (ret[i] >= distance)
ret[i] = distance;
distance++;
}
left = startIndex;
// 此处注意,查找下一个 C 的位置时,要排除掉当前的 C
// 否则程序会陷入死循环
startIndex = S.IndexOf(C, left + 1);
}
return ret;
}
}
提交后在 LeetCode 榜单上发现另外一个解法
public class Solution
{
public int[] ShortestToChar(string S, char C)
{
var len = S.Length;
var retval = new int[len];
var lastIdx = -len;
for (int m = 0; m < len; m++)
{
if (S[m] == C) lastIdx = m;
retval[m] = m - lastIdx;
}
lastIdx = len * 2;
for (int m = len - 1; m >= 0; m--)
{
if (S[m] == C) lastIdx = m;
retval[m] = Math.Min(lastIdx - m, retval[m]);
}
return retval;
}
}
原文地址:https://www.cnblogs.com/Downstream-1998/p/10352803.html
时间: 2024-10-10 13:06:43