zoukankan      html  css  js  c++  java
  • 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.

    解题思路:

    一直想有没有什么简便的方法,没想出来,就用了笨方法。

    代码:

     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             if (S[i] == C)
     7                 index.push_back(i);
     8         }
     9         for (int i = 0; i < S.size(); ++i){
    10             int length = INT_MAX;
    11             if (S[i] == C) {
    12                 res.push_back(0);
    13                 continue;
    14             }
    15             for (int j = 0; j < index.size(); ++j) {
    16                 if (abs(index[j] - i ) < length)
    17                     length = abs(index[j] - i);
    18                 else
    19                     break;
    20             }
    21             res.push_back(length);
    22         }
    23         return res;
    24         
    25     }
    26     vector<int> index;
    27 };

     


    PS:

    看了其他人的解法,有一方法很棒,分享下:

     1 vector<int> shortestToChar(const string& s, char c) {
     2     int size = s.size(), lastLocation = -1;
     3     vector<int> ret (size, INT_MAX);
     4     for (int i = 0; i < size; ++i) {
     5         if (s[i] == c) lastLocation = i;
     6         if (lastLocation != -1) ret[i] = i - lastLocation;
     7     }
     8     for (int i = lastLocation - 1; i >= 0; --i) {
     9         if (s[i] == c) lastLocation = i;
    10         ret[i] = min(lastLocation - i, ret[i]);
    11     }
    12     return ret;
    13 }
  • 相关阅读:
    React Native组件左右两端展示(flex:1、justifyContent:'space-between')
    iOS 蓝牙开发详解(基本知识、相关类图、交互流程)
    iOS 蓝牙开发 Mac地址问题
    AFNetwork监听网络失效
    查看linux系统版本和cpu
    docker常用命令
    docker 常用命令--镜像删除
    docker部署nginx
    常见数据库会话查询脚本
    DB性能瓶颈分析思路
  • 原文地址:https://www.cnblogs.com/gsz-/p/9470632.html
Copyright © 2011-2022 走看看