内容中心

2026年热门的红外光谱仪ATR销售厂家-天津恒创立达科技发展有限公司

To solve this problem, we need to compute the minimum distance from each character in a given string to the nearest occurrence of a specified character.

Approach

The approach involves two passes over the string:

  1. Left to Right Pass: Traverse the string from the start to the end. For each character, if it is the target character, record its position. For other characters, calculate the distance to the last encountered target character.
  2. Right to Left Pass: Traverse the string from the end to the start. For each character, if it is the target character, record its position. For other characters, update the distance to the minimum of the current distance (from the left pass) and the distance to the next encountered target character.

This two-pass method ensures that we efficiently compute the minimum distance for each character by considering both directions.

Solution Code

def shortestToChar(s: str, c: str) -> list[int]:
    n = len(s)
    dist = [n] * n  # Initialize with a value larger than max possible distance

    # Left to right pass
    last = -n  # To handle positions before the first occurrence of c
    for i in range(n):
        if s[i] == c:
            last = i
            dist[i] = 0
        else:
            dist[i] = i - last

    # Right to left pass
    last = 2 * n  # To handle positions after the last occurrence of c
    for i in range(n-1, -1, -1):
        if s[i] == c:
            last = i
            dist[i] = 0
        else:
            dist[i] = min(dist[i], last - i)

    return dist

Explanation

  1. Initialization: We start by initializing an array dist with a value larger than the maximum possible distance (length of the string) to ensure any valid distance will be smaller.
  2. Left to Right Pass: We keep track of the last position where the target character c was found. For each character, if it's not c, we compute the distance to the last c and store it in dist.
  3. Right to Left Pass: We again track the last position of c but from the end. For each character, if it's not c, we update the distance to the minimum of the current value (from left pass) and the distance to the next c (from the right).

This method efficiently computes the required distances in linear time, O(n), where n is the length of the string, making it optimal for large inputs.

Example: For s = "loveleetcode" and c = "e", the output is [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0], which is correctly computed using the two-pass approach.

This solution handles all edge cases, including when the target character is at the start, end, or appears multiple times in the string. It also works if the target character is the only character in the string.

天津恒创立达科技发展有限公司

天津恒创立达科技发展有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?