[LeetCode] Shortest Distance to a Character

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

Note:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.

查找数组中元素与目标元素的最短距离

1. 使用数组index存储目标元素在源字符串中的全部索引。

2. 对于源字符串中字符x,求距离在index中所有元素的最小值。

3. 将这个最小值放入结果数组中。

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        if (S.empty() || C == ' ')
            return {};
        int n = S.size();
        vector<int> res(n);
        vector<int> index_of_C;
        for (int i = 0; i < n; ++i)
        {
            if (S[i] == C)
                index_of_C.push_back(i);
        }
        for (int i = 0; i < n; ++i)
        {
            int dis = INT_MAX;
            for (auto& idx : index_of_C)
            {
                dis = min(dis, abs(idx-i));
            }
            res[i] = dis;
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/immjc/p/9149234.html
今日推荐