一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第19天,点击查看活动详情。
题目描述
这是 LeetCode 上的 821. 字符的最短距离 ,难度为 简单。
Tag : 「模拟」、「BFS」
给你一个字符串 s
和一个字符 c
,且 c
是 s
中出现过的字符。
返回一个整数数组 answer
,其中
且
是 s
中从下标
到离它 最近 的字符 c
的 距离 。
两个下标
和
之间的 距离 为 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 。
复制代码
示例 2:
输入:s = "aaab", c = "b"
输出:[3,2,1,0]
复制代码
提示:
-
和
c
均为小写英文字母 - 题目数据保证
c
在s
中至少出现一次
遍历
根据题意进行模拟即可:两次遍历,第一次找到每个
左边最近的 c
,第二次找到每个
右边最近的 c
。
代码:
class Solution {
public int[] shortestToChar(String s, char c) {
int n = s.length();
int[] ans = new int[n];
Arrays.fill(ans, n + 1);
for (int i = 0, j = -1; i < n; i++) {
if (s.charAt(i) == c) j = i;
if (j != -1) ans[i] = i - j;
}
for (int i = n - 1, j = -1; i >= 0; i--) {
if (s.charAt(i) == c) j = i;
if (j != -1) ans[i] = Math.min(ans[i], j - i);
}
return ans;
}
}
复制代码
- 时间复杂度:
- 空间复杂度:
BFS
起始令所有的
,然后将所有的 c
字符的下标入队,并更新
,然后跑一遍 BFS
逻辑,通过
是否为
来判断是否重复入队。
代码:
class Solution {
public int[] shortestToChar(String s, char c) {
int n = s.length();
int[] ans = new int[n];
Arrays.fill(ans, -1);
Deque<Integer> d = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
if (s.charAt(i) == c) {
d.addLast(i);
ans[i] = 0;
}
}
int[] dirs = new int[]{-1, 1};
while (!d.isEmpty()) {
int t = d.pollFirst();
for (int di : dirs) {
int ne = t + di;
if (ne >= 0 && ne < n && ans[ne] == -1) {
ans[ne] = ans[t] + 1;
d.addLast(ne);
}
}
}
return ans;
}
}
复制代码
- 时间复杂度:
- 空间复杂度:
最后
这是我们「刷穿 LeetCode」系列文章的第 No.821
篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:github.com/SharingSour… 。
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。