leetcode 821. 字符的最短距离(Shortest Distance to a Character)

题目描述:

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

示例 1:

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

说明:

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

解法:

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        int sz = S.size();
        vector<int> res(sz, sz);
        int pre = -sz;
        for(int i = 0; i < sz; i++){
            if(S[i] == C){
                pre = i;
            }
            res[i] = min(res[i], i - pre);
        }
        
        int pst = 2*sz;
        for(int i = sz-1; i >= 0; i--){
            if(S[i] == C){
                pst = i;
            }
            res[i] = min(res[i], pst - i);
        }
        return res;
    }
};

转载于:https://www.cnblogs.com/zhanzq/p/10637779.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值