zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    Django路由系统
    修改数据库时区问题
    Django框架篇
    前端css
    前端html
    前端初识
    数据库3
    数据库2
    数据库1
    数据库初识
  • 原文地址:https://www.cnblogs.com/immjc/p/9149234.html
Copyright © 2011-2022 走看看