力扣每日一题2022-04-19简单题:字符的最短距离


题目描述

字符的最短距离


思路

遍历

最简单的思路就是对于每个位置正着遍历一遍,再反着遍历一遍,分别记录两次遍历它离前面遍历到的最近的字符c的距离,取最小值存到ans数组中即可。

Python实现
class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        n = len(s)
        ans, idx = [0] * n, -n
        for i, ch in enumerate(s):
            if ch == c:
                idx = i
            ans[i] = i - idx
        idx = 2*n
        for i in range(n-1, -1, -1):
            if s[i] == c:
                idx = i
            ans[i] = min(ans[i], idx-i)
        return ans
Java实现
class Solution {
    public int[] shortestToChar(String s, char c) {
        int n = s.length();
        int[] ans = new int[n];
        int idx = -n;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == c) {
                idx = i;
            }
            ans[i] = i - idx;
        }
        idx = 2*n;
        for (int i = n-1; i >= 0; i--) {
            if (s.charAt(i) == c) {
                idx = i;
            }
            ans[i] = Math.min(ans[i], idx-i);
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值