leetcode821-Shortest Distance to a Character

发布于:2024-04-24 ⋅ 阅读:(24) ⋅ 点赞:(0)

题目

给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。
返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。
两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。
示例 1:

输入:s = “loveleetcode”, c = “e”
输出:[3,2,1,0,1,0,0,1,2,2,1,0]
解释:字符 ‘e’ 出现在下标 3、5、6 和 11 处(下标从 0 开始计数)。
距下标 0 最近的 ‘e’ 出现在下标 3 ,所以距离为 abs(0 - 3) = 3 。
距下标 1 最近的 ‘e’ 出现在下标 3 ,所以距离为 abs(1 - 3) = 2 。
对于下标 4 ,出现在下标 3 和下标 5 处的 ‘e’ 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1 。
距下标 8 最近的 ‘e’ 出现在下标 6 ,所以距离为 abs(8 - 6) = 2 。

分析

这道题目很直接的思路就是依次遍历数组每个元素,分别向左遍历向右遍历,找到和字符c相同的元素然后更新当前元素到字符c之间的距离。这种方法是更新非c字符的距离
还有一种时间复杂度更小的方法,我们先正序遍历数组,等找到字符c以后我们更新每个元素到c的距离,一遍下来有些元素已经有了到字符c的最短距离了,然后倒叙遍历数组,用类似的思路并且与第一遍正序遍历的结果也进行比较寻找最小值

import java.util.Arrays;

public class shortestDistancetoaCharacter{
	public static void main(String[] args) {
		String s = "loveleetcode";
		char c = 'e';
		int[] res = getShortest(s,c);
		for(int i = 0;i<res.length;i++) {
			System.out.println(res[i]);
		}
	}
	public static int[] getShortest(String str,char c) {
		int len = str.length();
		int[] res = new int[len];
		Arrays.fill(res,Integer.MAX_VALUE);
		for(int i = 0,j = -1;i<len;i++) {
			if(str.charAt(i) == c) {
				res[i] = 0;
				j = i;
			} else if(j != -1) {
				res[i] = i - j;
			}
		}
		for(int i = len - 1,j = -1;i>= 0;i--) {
			if(str.charAt(i) == c) {
				res[i] = 0;
				j = i;
			} else if(j != -1) {
				res[i] = Math.min(res[i],j-i);
			}
		}
		return res;
	}
}

网站公告

今日签到

点亮在社区的每一天
去签到