其他分享
首页 > 其他分享> > leetcode 821. 字符的最短距离(Shortest Distance to a Character)

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]

说明:


解法:

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;
    }
};

标签:pre,Distance,sz,int,res,Character,字符,字符串,821
来源: https://www.cnblogs.com/zhanzq/p/10637779.html