Shortest Distance to a Character 字符的最短距离

本文介绍了一种算法,用于计算字符串中每个字符到指定字符的最短距离,并通过两次遍历优化效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。

示例 1:

输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

说明:

  1. 字符串 S 的长度范围为 [1, 10000]
  2. C 是一个单字符,且保证是字符串 S 里的字符。
  3. S 和 C 中的所有字母均为小写字母。

思路:遍历两次数组,第一次从左向右判断S中任意字符离左边最近的C的距离,然后再从右向左遍历判断S中任意字符离右边最近的C的距离,两次遍历取最小值即可。

参考代码:

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
	int n = S.size();
	vector<int> result(n,n);
	int pos = -n;
	for (int i = 0; i < n; i++) {
		if (S[i] == C) pos = i;
		result[i] = min(result[i], abs(i - pos));
	}
	for (int i = n-1; i >=0; i--) {
		if (S[i] == C) pos = i;
		result[i] = min(result[i], abs(i - pos));
	}
	return result;
    }
};






给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。

示例 1:

输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

说明:

  1. 字符串 S 的长度范围为 [1, 10000]
  2. C 是一个单字符,且保证是字符串 S 里的字符。
  3. S 和 C 中的所有字母均为小写字母。
在Python中,我们可以使用Dijkstra算法或A*搜索算法来寻找图中的路径。这里以Dijkstra算法为例,因为它是常用的求解单源路径的问题。我们将假设你有一个邻接矩阵或邻接列表表示的图结构。 首先,你需要安装`networkx`库,如果尚未安装,可以使用pip安装: ```bash pip install networkx ``` 然后,你可以创建一个函数来找出从节点A到节点B的路径: ```python import heapq from collections import defaultdict def dijkstra(graph, start_node): distances = {node: float('inf') for node in graph} distances[start_node] = 0 shortest_paths = {} visited = set() def get_neighbors(node): return [neighbor for neighbor, weight in graph[node].items() if neighbor not in visited] def relax(distance, current_node, neighbor_node): nonlocal distances new_distance = distance + graph[current_node][neighbor_node] if new_distance < distances[neighbor_node]: distances[neighbor_node] = new_distance shortest_paths[neighbor_node] = current_node while len(shortest_paths) < len(graph): min_distance_node = None for node, distance in distances.items(): if node not in visited and (min_distance_node is None or distance < distances[min_distance_node]): min_distance_node = node if min_distance_node is None: break visited.add(min_distance_node) neighbors = get_neighbors(min_distance_node) for neighbor in neighbors: relax(distances[min_distance_node], min_distance_node, neighbor) return distances, shortest_paths # 使用示例 graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } # 这是一个简单的图示例,键是节点名,值是字典,键是邻居节点,值是边的权重 shortest_distances, path = dijkstra(graph, 'A') print(f"最短距离: {shortest_distances['B']}") print(f"途径节点: {path['B']}") # 输出从A到B的路径 ``` 在这个例子中,`graph`是一个字典,其中每个键代表一个节点,键对应的值是一个字典,表示该节点的相邻节点及其边的权重。`dijkstra`函数返回最短距离和包含路径的字典。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值