[Solution] 821. Shortest Distance to a Character

时间:2023-03-08 20:17:55
  • 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:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C 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;
}
}