[leetcode]821. Shortest Distance to a Character

[leetcode]821. Shortest Distance to a Character


Analysis

中午吃啥~—— [啊啊啊~]

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
第一次从前往后遍历,找到每个字符和其左边C的距离,第二次从后往前遍历,找到每个字符和其右边C的距离,然后求最小值。

Implement

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        int len = S.size();
        vector<int> res(len, len);
        int pos = -len;
        int dis;
        for(int i=0; i<len; i++){
            if(S[i] == C)
                pos = i;
            dis = abs(i-pos);
            res[i] = min(res[i], dis);
        }
        for(int i=len-1; i>=0; i--){
            if(S[i] == C)
                pos = i;
            dis = abs(i-pos);
            res[i] = min(res[i], dis);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81258464