leetcode 387. First Unique Character in a String(字符串中第一个独一无二的字母)

LeetCode --- 387. First Unique Character in a String解题报告 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note:You ... 阅读详情

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = “leetcode”
Output: 0
Example 2:

Input: s = “loveleetcode”
Output: 2
Example 3:

Input: s = “aabb”
Output: -1

找出字符串s 中只出现一次的字母,返回它的index。
如果没有,返回-1。

思路:

网上有个1ms的解法,用到了字符串自带的indexOf, lastIndexOf函数,
如果它俩相等,证明只出现了一次,更新最小的index即可。

public int firstUniqChar(String s) {
    int result=s.length();
    
    for(char c='a';c<='z';c++){
        int firstIndex=s.indexOf(c);
        if(firstIndex!=-1 && firstIndex==s.lastIndexOf(c)){
            result=Math.min(result, firstIndex);
        }
    }
    
    return result==s.length()?-1:result;
}

这里我们不用字符串自带的函数,
因为字母只有26个,所以用一个数组记录下每个字母出现的次数,
然后找到次数为1的字母,它出现的最小index即可,

找最小index岂不是又要把s 遍历一次?no,
还是用一个数组记录下每个字母出现的最小index,
直接找到对应的index, 然后更新最小的index即可。

public int firstUniqChar(String s) {
    int[] cnt = new int[26];
    int[] firstIdx = new int[26];
    int res = s.length();
        
    Arrays.fill(firstIdx, -1);
    
    for(int i = 0; i < s.length(); i++) {
        int idx = s.charAt(i) - 'a';
        cnt[idx] ++;
        if(firstIdx[idx] == -1) firstIdx[idx] = i;
    }
    
    for(int i = 0; i < 26; i++) {
        if(cnt[i] == 1) res = Math.min(res, firstIdx[i]);
    }
    
    return (res == s.length() ? -1 : res);
}
仿真每日一练 | Workbench如何在网格节点施加载荷 打开Workbench 2020 R2,在分析系统中双击静力分析工程项目,双击Geometry打开Design Modeler,在菜单栏的单位(Units)修改为毫米(Millimeter),在XY平面创建草图,在草图内绘制矩形并标注尺寸,拉伸长方体,如图1所示。:单个零部件,无连接关系,但需定义一个节点组件,如图5所示,选择Create Named Selection。对添加的节点组件施加Y方向50N的力,如图8所示。1-1-3.有限元系统模型构建。1-1-1.几何模型构建。1-1-2.材料定义。 阅读详情

相关推荐

51单片机定时器的原理、应用与编程实现

本文系统介绍了51单片机定时器的基本原理与应用。首先阐述了定时器的工作原理,包括定时模式和计数模式的区别。然后详细讲解了定时器的四种工作模式(方式0-方式3)及其适用场景,并分析了相关寄存器(TMOD、TCON、THx/TLx)的功能设置。文章还给出了定时器编程的具体步骤,包括初始化、计数初值计算和示例代码。最后通过LED闪烁、PWM波形产生、脉冲计数等实际应用案例,展示了定时器的多样化应用。掌握这些知识对嵌入式系统开发具有重要意义。

2501_91227323的博客 1537

LeetCode387—First Unique Character in a String

LeetCode387 First Unique Character in A String

上善若水 1866

Star CCM+中的图片自动保存设置

图片自动保存设置

2201_75375391的博客 3456

leetcode 387. First Unique Character in a String

目录 一、问题描述 二、代码实现 1、两遍遍历 2、一遍遍历 https://leetcode.com/problems/first-unique-character-in-a-string/ 返回给定字符串第一个只出现一次的字符的下标,不存在则返回-1 一、问题描述 测试用例: s = "leetcode" return 0. s = "loveleetcode...

小景的博客 217

【Kafka】kafka 卡死 Discovered coordinator xx:9092 (id: xxx rack: null) for group xxx

1.背景 构建了一个kafka消费组,然后 2020-12-09 21:55:22 [XNIO-1 task-120] INFO o.a.k.c.consumer.ConsumerConfig - ConsumerConfig values: metric.reporters = [] metadata.max.age.ms = 300000 partition.assignment.strategy = [org.apache.kafka.clients.consumer.RangeAssign.

九师兄 1万+

用 ABAP 驾驭 OAuth 2.0:从 Authorization Code 到 SAML Bearer 的全栈落地指南

ABAP平台OAuth 2.0客户端开发实践 本文为SAP开发者详细解析ABAP平台内置OAuth 2.0客户端的使用方法,涵盖四种授权流的最佳实践: 授权流选择: Authorization Code:适用于用户交互场景 SAML 2.0 Bearer:适合已有SAML体系的企业 Client Credentials:系统间通信 Password Credentials:过渡方案(不推荐) 配置流程: 通过SE80定义Client Profile 使用SOAUTH2_CLIENT/OA2C_CONFIG配

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 317

387. First Unique Character in a String*

387. First Unique Character in a String* https://leetcode.com/problems/first-unique-character-in-a-string/description/ 题目描述 Given a string, find the first non-repeating character in it and return it’s...

珍妮的选择的博客 264

CLASSB类移植(满足IEC 60730-1和60355-1标准)

针对软件认证需要满足IEC 60730-1和60335-1标准,ST公司专门提供的软件扩展包X-CUBE-CLASSB,它包含自测库和文档,支持多种STM32系列芯片,通过预集成测试库和标准化流程,帮助开发者快速满足国际安全标准,适用于家电、工业控制等高可靠性场景。ClassB软件包程序检测内容分为两个主要部分:启动时的自检和运行时的周期自检,MCU在上电的时候会进行复位启动,在启动完成以后会进行运行自检。

m0_61973119的博客 1415

Leetcode PHP题解--D100 387. First Unique Character in a String

D100 387. First Unique Character in a String 题目链接 387. First Unique Character in a String 题目分析 返回给定字符串中第一个只出现了一次的单词下标。 若没有,则返回-1。 思路 把遇到的单词存进两个数组。 ...

247

人工智能在软件测试中的广泛应用领域

人工智能在软件测试中的应用领域涵盖了自动化测试、缺陷预测和缺陷检测、智能化测试报告生成等方面。以上提供的示例代码只是其中的一小部分,实际上,人工智能在软件测试中还有许多其他的应用。通过结合人工智能和软件测试,可以提高测试效率和质量,减少测试工作的人力成本,并帮助开发人员更好地理解和改进软件产品。人工智能(Artificial Intelligence,简称AI)在软件测试领域的应用越来越广泛。下面将介绍几个人工智能在软件测试中的主要应用领域,并提供一些相关的源代码示例。

FycPerformance的博客 466

Linux | i.MX6ULL Mqtt 移植教程

本文介绍了MQTT协议在物联网中的应用及其实现工具Mosquitto的移植过程。使用Ubuntu 16.04环境和gcc交叉编译器,详细说明了从X86平台安装测试到ARM开发板移植的完整步骤。重点包括:Mosquitto的安装配置、服务启动测试方法、依赖库openssl和libuuid的交叉编译过程、路径参数修改要点,以及最终在开发板上的功能测试验证。文中提供了具体的命令操作和路径修改示例,强调路径一致性对编译成功的重要性。该移植方案实现了轻量级MQTT协议在嵌入式设备中的应用。

Qt历险记,专注Qt技术,三年医疗设备研发经验,1年机器视觉研发经验,半年柔性传感研发经验。 156

【LeetCode】387. First Unique Character in a String 字符串中的第一个唯一字符(Easy)(JAVA)

【LeetCode】387. First Unique Character in a String 字符串中的第一个唯一字符(Easy)(JAVA) 题目地址: https://leetcode.com/problems/first-unique-character-in-a-string/ 题目描述: Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist,

qq_16927853的博客 184

华为OD机试真题 新系统【查找能被整除的最大整数】

华为OD新系统机试真题【查找能被整除的最大整数】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【查找能被整除的最大整数】

qq_45776114的博客 695

LeetCode 387. 字符串中的第一个唯一字符(First Unique Character in a String)

387. 字符串中的第一个唯一字符 LeetCode387. First Unique Character in a String 题目描述 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 Java 实现 cla...

weixin_30830327的博客 263

深度学习工具包 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")

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

leetcode 387. First Unique Character in a String 详解 python3

一.问题描述 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. No...

CSerwangjun的博客 424

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

leetcode[387]First Unique Character in a String

问题:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。 输入:一个字符串(仅包含英文小写字母) 输出:第一个不重复的字符索引(不存在则返回-1) 思路: 遍历一遍字符串,利用hash表存储,每个字符为key时,value加1。 然后,正序遍历一遍字符串,如果value为1,则返回其索引。 (或者,遍历一遍hash表,如下第一个代码,判断是否为不重复的数字,比较得到最小的索...

Black Mamba的博客 191

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode String 387 First Unique Character in a String

387. First Unique Character in a String Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1. Examples: s = “leetcode” return 0. s = “lov...

Yi Jiao's Blog 141

【LeetCode】387. First Unique Character in a String 字符串中的第一个唯一字符(Easy)(JAVA)每日一题

【LeetCode】387. First Unique Character in a String 字符串中的第一个唯一字符(Easy)(JAVA) 题目地址: https://leetcode-cn.com/problems/first-unique-character-in-a-string/ 题目描述: Given a string, find the first non-repeating character in it and return its index. If it doesn’t exi

qq_16927853的博客 220

LeetCode 387 First Unique Character in a String 字符串中的第一个唯一的字母 C语言

387. First Unique Character in a String Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1. . 从给定的字符串中找到第一个不重复的字母,并输出其在字符串中的指针位置(第一个字母的位...

高能粒子的博客 225

LeetCode笔记:387. First Unique Character in a String

找到一个字符串中第一个只出现一次的字母

Minecraft 2365

LeetCode 387. First Unique Character in a String 题解(C++)

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

prayyojay的博客 468

02.leetcode-387.First Unique Character in a String

题目: 387.字符串中的第一个唯一字符Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. 找出字符串中的第一个唯一(不重复)字符;不存子啊返回-1 分析: 暴力破解时间复杂度依旧为O(n^2); 此外还有许多其他方法,这里就不介绍了,包括hash; 解决方案: 循环26个字母,统计每个字母出现次数为1的字母.

ScorpC的博客 274

LeetCode 387. First Unique Character in a String

题目: 给定一个字符串,找到其中第一个非重复字符并返回它的索引。如果不存在,返回-1。 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. s = "leetcode" return 0. s = "l...

冲鸭!!! 166

LeetCode - 387. First Unique Character in a String

链接 387. First Unique Character in a String 题意 给定一个字符串(只有小写字母),返回其中第一个没有重复的字母的下标 思路 把这些字母转成数字存入数组,值为出现的次数。按照字符串的字母顺序遍历,当值为1时返回即可。 代码 Java : public class Solution { public int firstUniqChar(Str...

157

Leetcode|387. First Unique Character in a String字符串中的第一个唯一字符.java

题目 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 示例 : s = “leetcode” 返回 0 s = “loveleetcode” 返回 2 提示: 你可以假定该字符串只包含小写字母。 标签 字符串;哈希表 解题思路 方法:哈希表 先将每个字符出现的次数统计到哈希映射中,再进行第二次遍历,找出只出现一次的字符,返回其索引即可。 代码 public class Leetcode387_FirstUniqueCharacterIn_a_String {

梦晨涌京 130

java字符串hash唯一_LeetCode 387: 字符串中的第一个唯一字符 First Unique Character in a String...

LeetCode 387: 字符串中的第一个唯一字符 First Unique Character in a String题目:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。Given a string, find the first non-repeating character in it and return it's index. If it...

weixin_42165490的博客 258
上一篇: ESANet语义分割与realsense D455的结合
下一篇: leetcode 804. Unique Morse Code Words(独特的摩斯码单词)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址