• LeetCode 821. Shortest Distance to a Character


    821. 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.

    这道题要求给定字符串中每个字符和字符串中某个特定字符C的最小距离,题目不是很难,但是要仔细分析,我的思路是从头到尾遍历字符串,对于每一个字符,都分别向前向后遍历,分别比较两个方向上与字符C的距离,取最小值,最好时间复杂度为O(N),最差为O(N^2)

     1 class Solution {
     2 public:
     3     vector<int> shortestToChar(string S, char C) {
     4         vector<int> res;
     5         for (int i = 0; i < S.size(); i++)
     6         {
     7             int k = i;
     8             int dis = INT_MAX;
     9             while (k >= 0)
    10             {
    11                 if (S[k] == C)
    12                 {
    13                     dis = min(dis, i - k);
    14                     break;
    15                 }
    16                 k--;
    17             }
    18             k = i;
    19             while (k <= S.size() - 1)
    20             {
    21                 if (S[k] == C)
    22                 {
    23                     dis = min(dis, k - i);
    24                     break;
    25                 }
    26                 k++;
    27             }
    28             res.push_back(dis);
    29         }
    30         return res;
    31     }
    32 };
  • 相关阅读:
    MSSQL复制表
    分享职场心得《7》
    分享职场心得《2》
    分享职场心得《3》
    免费收录网站搜索引擎登录入口最新版
    读写分离,读写分离死锁解决方案
    分享职场心得《5》
    分享职场心得《6》
    分享职场心得《1》
    分享职场心得《4》
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8997724.html
Copyright © 2020-2023  润新知