[LeetCode] 821. Shortest Distance to a Character

什么是三极管推挽电路 当没有信号输入时,电源通过PNP三极管EB间的二极管,然后通过NPN三极管BE间而二极管到地,这时这两个三极管都是导通的,三极管很容易由于电流过大而损坏。当输入信号为VCC时,上面的三极管导通,下面的三极管截止,输出信号为VCC-0.7V,这个0.7V就是上面NPN三极管BE间的导通压降。比如上面的三极管导通,那么输出电压就是输入电压减去0.7V,所以下面的PNP三极管由于基极电压大于发射极电压,是不会导通的。这是一个三极管推挽电路,上面是一个NPN的三极管,下面是一个PNP的三极管。 阅读详情

821. Shortest Distance to a Character (到字符的最短距离)



1. 题目翻译

给定一个字符串S,和一个字符C。求出S中每个字符到最近的字符C的距离。

例子:

输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

备注:

  1. S的长度范围 [1, 10000]。
  2. C是单个字符,并且保证在S中存在。
  3. S与C中的所有字符都是小写字母。

2. 解题方法

首先建立一个数组flag将S中所有C存在的位置保存下来。然后遍历S字符串,将其与C中保存的位置依次求距离(差的绝对值),然后保存下来最短距离就可以。

3. 代码

//Runtime: 15ms
class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        vector<int> res(S.size(),0);
        vector<int> flag;
        for(int i=0;i<S.size();i++)
            if(S[i]==C)
                flag.push_back(i);

        for(int i =0;i<S.size();i++){
            if(S[i]!=C){
                int mind = S.size();
                for(int j = 0;j<flag.size();j++)
                    mind = mind<abs(flag[j]-i)?mind:abs(flag[j]-i);
                res[i]=mind;
            }
        }
        return res;
    }
};
别再只用GPS了!用Android手机传感器实现室内步行轨迹记录(避坑指南) 本文详细介绍了如何利用Android手机传感器(如加速度计、陀螺仪和磁力计)实现室内步行轨迹记录,克服GPS在室内的局限性。通过传感器数据采集、步态检测、航向估计和轨迹绘制等步骤,结合避坑指南和优化技巧,帮助开发者高效构建室内定位应用。 阅读详情

相关推荐

机器人C++开源库The Robotics Library (RL)使用手册(三)

进入VS工程,我们先看看这些功能函数及其依赖库的分布关系:rl命名空间下,主要有八大模块。搞定VS后将逐个拆解。

qq_34839823的博客 1736

leetcode 821. 字符的最短距离(Shortest Distance to a Character)

给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。 示例 1: 输入: S = "loveleetcode", C = 'e' 输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] 说明: 字符串 S 的长度范围为 [1, 10000]。 C 是一个单字符,且保证是字符串 S 里的字符。 ...

一叶之修的博客 284

Doris Streamloader安装教程

Doris Streamloader 是一款用于将数据导入 Doris 数据库的专用客户端工具。本文介绍其在centos7环境下的安装过程

qq_44540985的博客 1089

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

xdhc的博客 672

光通信仿真入门:手把手教你用VPI和Matlab搭建第一个联合仿真系统(含避坑指南)

本文详细介绍了如何使用VPI和Matlab搭建光通信联合仿真系统,涵盖软件配置、链路搭建、数据交互等关键环节,并提供常见问题的解决方案。特别适合初学者快速掌握光通信仿真技术,避免常见错误,提升仿真效率。

weixin_28733637的博客 377

汇川Easy 301 和MCGS进行Modbus RTU通讯(485)浮点数读取和写入

4DF0001对应寄存器D0,4DF0003对应寄存器D2。注意:要选com2口,com1口是232通讯。

qq_61916672的博客 2900

LeetCode 821. Shortest Distance to a Character 字符的最短距离

题目:给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。示例 1:输入: S = "loveleetcode", C = 'e' 输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] 说明:字符串 S 的长度范围为 [1, 10000]。C 是一个单字符,且保证是字符串 S 里的字符。S 和 C 中的所有...

zhangzhetaojj的博客 782

手把手教你用STM32实现SPWM逆变器控制(附完整代码)

本文提供了一份基于STM32实现SPWM逆变器控制的完整实战指南。文章从硬件选型(如STM32F103C8T6、IR2104驱动器)入手,详细解析了利用定时器TIM1生成SPWM波形的核心原理与代码实现,并涵盖了驱动电路、全桥功率电路及LC滤波器的设计要点与调试技巧,旨在帮助读者从零构建一个可靠的单相全桥逆变器系统。

weixin_29208327的博客 589

leetcode 821. 字符的最短距离 Shortest Distance to a Character python 多种思路,最简代码

class Solution: def shortestToChar(self, S, C): &quot;&quot;&quot; :type S: str :type C: str :rtype: List[int] &quot;&quot;&quot; # method one 笨方法,计算量大 # dic = {}

Jasmine_dream 779

多旋翼飞行器设计与控制·Pixhawk4以及外部设备接线(笔记004)

笔记主要来源:Pixhawk 4 接线快速入门 目录 一、Pixhawk 4 的各个接口 二、接线图概览(重要传感器及外围设备) 三、飞控、GPS的安装和方向 四、电源 五、无线电遥控 六、数传电台(可选) 七、SD Card(可选) 八、电机以及其他外设 一、Pixhawk 4 的各个接口 FMU:Flight Management Unit 飞行管理组件 主 FMU 处理器:STM32F765 32 位 Arm® Cortex®-M7,216MHz,2MB...

猪猪的博客 1万+

windows使用jupyter notebook读取文件路径的几种方法和设置默认打开路径

简单分享小虎这段时间以来学到的jupyter notebook操作技巧。

狂小虎/Anthony Dave的博客 KuangXiaoHu's Blogs 1万+

python leetcode 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' Outp...

DreamerLHQ的博客 861

详解AUTOSAR:DaVinci Configurator配置CAN和UART数据协议解析器(RH850)(实战篇—1)

通过学习本篇博文项目,将会把所学的DaVinci Configurator知识系统串联起来。

不脱发的程序猿 2809

【Leetcode】821. Shortest Distance to a Character

题目地址: https://leetcode.com/problems/shortest-distance-to-a-character/ 给定一个字符串sss和一个sss中字母ccc,要求返回一个数组AAA,其中A[i]A[i]A[i]等于s[i]s[i]s[i]与与其距离最近的那个ccc的距离。 由于距离s[i]s[i]s[i]最近的ccc要么在其左边要么在其右边,所以可以用遍历两遍的方式,从左到右一遍,从右到左一遍,每次遍历用一个变量记录最新出现的ccc的位置,同时更新最短距离。代码如下: publi

数学、算法爱好者的博客 175

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LeetCode 821 Shortest Distance to a Character

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

博客 388

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode //C - 821. Shortest Distance to a Character

Summary: This problem requires computing the shortest distance from each character in a string s to the nearest occurrence of a specified character c. The solution involves two passes over the string: Left-to-right pass: Records the distance to the last se

Made in Code 783

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

LeetCode 821. Shortest Distance to a Character

LeetCode 821. Shortest Distance to a Character (Easy) 主要知识点:string;优先级:3

温迪今天刷题了吗 581

【LeetCode】821. Shortest Distance to a Character

题目:简述题目:    求一个数组,一次是S中的每个字母距离字符C的最短距离思路:    先记录字符C在S中的位置,然后遍历S,依次计算每个字符距离每个C的距离,取最小的那一个即可代码:public class shortestToChar821 { public static int abs(int n) {//求绝对值 if(n &gt;= 0) return n; else ...

Mint_r的博客 277

[leetcode] 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, ...

jing16337305的博客 249

leetcode 821. Shortest Distance to a Character

方法一: 把符合要求的字符的下标存储到一个容器里,然后将每个位置的下标与容器里的下标做差取绝对值,最小的那个值就是想要的。 class Solution { public int[] shortestToChar(String S, char C) { List<Integer> list = new ArrayList<>(); f...

xiaobailaji的博客 95

Leetcode 821. Shortest Distance to a Character

Leetcode 821. Shortest Distance to a Character

SnailTyan 249

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

weixin_32135877的博客 160

leetcode821-Shortest Distance to a Character

还有一种时间复杂度更小的方法,我们先正序遍历数组,等找到字符c以后我们更新每个元素到c的距离,一遍下来有些元素已经有了到字符c的最短距离了,然后倒叙遍历数组,用类似的思路并且与第一遍正序遍历的结果也进行比较寻找最小值。对于下标 4 ,出现在下标 3 和下标 5 处的 ‘e’ 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1。距下标 1 最近的 ‘e’ 出现在下标 3 ,所以距离为 abs(1 - 3) = 2。输出:[3,2,1,0,1,0,0,1,2,2,1,0]

我的程序人生 396
上一篇: [LeetCode] 561. Array Partition I
LLLZHLIU
博客等级 码龄10年 19粉丝 43原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值