LeetCode算法题-First Unique Character in a String(Java实现)

从“储能”到“信号”:拆解Buck电路中那颗不起眼的前馈电容,如何让电源更稳 本文深入解析Buck电路中前馈电容的关键作用,揭示其如何通过频域整形和零点补偿提升电源稳定性。从工作原理到工程实践,详细介绍了容值计算、布局布线及特殊场景调校策略,帮助工程师优化瞬态响应和纹波抑制。 阅读详情

这是悦乐书的第213次更新,第226篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第81题(顺位题号是387)。给定一个字符串,找到它中的第一个非重复字符并返回它的索引。 如果它不存在,则返回-1。例如:

输入:“leetcode”
输出:0

输入:“loveleetcode”,
输出:2

注意:您可以假设该字符串仅包含小写字母。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

直接使用字符串自带的方法indexOf和lastIndexOf,只要这两个方法找到当前字符所在的索引相等,即表示当前字符就是第一个非重复字符。

此解法的时间复杂度最好的情况是O(n),最坏的情况是O(n^2),空间复杂度是O(1)。

public int firstUniqChar(String s) {
    for(int i=0; i<s.length(); i++){
        if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
            return i;
        }
    }
    return -1;
}

03 第二种解法

因为题目给定范围是局限于小写字母,可以使用一个长度为26的数组,存储每个字符出现的次数,然后再去数组中找到只出现一次的字符,返回索引即可。

此解法的时间复杂度是O(n),空间复杂度是O(1),因为数组长度是定长的。

public int firstUniqChar2(String s) {
    int[] arr = new int[26];
    for (int i=0; i<s.length(); i++) {
        arr[s.charAt(i)-'a']++;
    }
    for (int j=0; j<s.length(); j++) {
        if (arr[s.charAt(j)-'a'] == 1) {
            return j;
        }
    }
    return -1;
}

04 第三种解法

此解法和第二种解法思路一致,区别在于数组容量变成了256,可以直接使用当前字符所表示的整数,而不必像第一种解法那样要减去字符小写a的值。

此解法的时间复杂度是O(n),空间复杂度是O(1),因为数组长度是定长的。

public int firstUniqChar3(String s) {
    int[] arr = new int[256];
    for (int i=0; i<s.length(); i++) {
        arr[s.charAt(i)]++;
    }
    for (int j=0; j<s.length(); j++) {
        if (arr[s.charAt(j)] == 1) {
            return j;
        }
    }
    return -1;
}

05 第四种解法

使用HashMap,key为当前字符,value为其出现次数,先使用循环,将所有字符put进去。再利用循环,判断当前字符作为key在map中的value是否等于1,如果相等,返回当前索引。

此解法的时间复杂度是O(n),空间复杂度是O(1),因为map中至多会存储26个键值对。

public int firstUniqChar4(String s) {
    Map<Character, Integer> map = new HashMap<Character, Integer>();
    for(int j=0; j<s.length(); j++){
        map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0)+1);
    }
    for (int i=0; i<s.length(); i++) {
        if (map.get(s.charAt(i)) == 1) {
            return i;
        }
    }
    return -1;
}

06 小结

算法专题目前已连续日更超过两个月,算法题文章81+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

YOLO26涨点改进 | 全网独家创新,注意力改进篇 | TGRS 2025 | 引入APCM自适应像素级协同机制,动态增强目标区域、抑制背景噪声,助力YOLO26做红外小目标检测有效涨点 本文提出一种基于APCM模块改进的YOLO26网络模型,通过像素级局部-全局协同建模动态增强目标特征并抑制背景噪声。APCM模块采用轻量化设计,无需复杂参数,在特征提取阶段有效提升目标区域特征表达质量,尤其适用于低对比度和复杂场景下的目标检测。实验表明,该方法能显著提高小目标检测精度和模型鲁棒性,同时保持较低计算开销。模块通过局部特征分支和全局特征分支的协同融合,实现了对红外小目标的有效增强,在NUAA-SIRST和IRSTD-1K数据集上性能优于现有方法。文章还提供了完整的代码实现和配置指南。 阅读详情

相关推荐

拆解大疆Osmo Pocket:聊聊微型云台里那几根比头发丝还细的线,以及它为啥一开机就‘摇头晃脑’

本文深入拆解大疆Osmo Pocket微型云台的精密硬件结构,揭秘其开机自检时‘摇头晃脑’的奥秘。通过分析无刷电机、霍尔传感器和46AWG同轴线等核心组件,展现了大疆在微型云台设计中的工程智慧与创新技术,特别是FOC控制和陀螺仪的应用,实现了0.1°级的姿态控制精度。

weixin_27869497的博客 671

LeetCode刷题 - Java常用输入输出

LeetCode刷题 - Java常用输入输出 基本语法 导包 import java.util.Scanner; //或者直接导入下面两个包 import java.util.*; import java.io.*; 常用输入 Scanner sc = new Scanner(System.in); //读一个整数 int n = sc.nextInt(); //读一个字符串,遇到分号则输入终止 String s = sc.next(); //读一个浮点数 double t = sc.nextDoubl

qq_42874319的博客 4514

[事件相机1]2024CVPR:Event Stream-based Visual Object Tracking: A High-Resolution Benchmark Dataset

作者:Xiao Wang, Shiao Wang, Chuanming Tang, Lin Zhu, Bo Jiang, Yonghong Tian, Jin Tang代码:https://github.com/Event-AHU/EventVOT_Benchmark。

m0_37412775的博客 1708

387. First Unique Character in a String Java

1、题目来源:点击打开链接 2、题目: 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"

0_o_c 950

单片机如何获得5V电源

在单片机实际设计中,有时会需要在电路中用到5V电压源,那么这个常见的实验需求有哪些办法解决呢,我综合网上的资料,概括一下: 1)USB    这种方法在我们直接将单片机板与电脑连接调试的时候,算是简单又方便的办法了,但如果我所要得到的成品不直接连接外部的器件,这就得舍弃。     常用的,USB/5V插头线,这是一种专门的电源线,一端是USB通用接口,可以直插USB端口,另一端是内正外负电压

Echo_Ana的博客 3万+

【72】【OpenCV C++ & C#】 将cv::Mat 图像转换成imgINFO 传给c#在winform上显示,OpenCV C++如何将处理后的图像传给C#呢? 如何获取图像信息呢?

本文介绍了通过OpenCV C++处理图像后传递给C#的方法。首先定义了一个结构体imgINFO存储图像信息(数据指针、宽高、通道数等),然后通过getImgInfo函数将cv::Mat转换为该结构体。文章特别指出当图像宽度不能被4整除时可能出现失真问题,并给出了两种解决方案:调整输入图像或创建新的对齐图像。此外还解释了img.step和img.cols*img.elemSize()的关系,说明它们在大多数情况下是相等的。最后提到需要通过DLL将结构体传递给C#(具体方法参见其他文章)。

程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。 697

刷leetcode中Java常用API总结

在刷题过程中的一些常用API调用,记录下来,方便复习。   一:Integer 类 1.String -> int:int value = Integer.parseInt(str); 2.将str转换成二进制的int: int binary = Integer.parseInt(str,2); 3.十进制转二进制:String binaryN=Integer.toBinaryString(N);   二:String 类 1.Object -> String:String

qq_35941161的博客 2156

带有HSE组件的S32系列芯片中各子系统如何依次启动?

仔细阐述了上电后各个子系统的启动顺序,并给出了详细的启动步骤流程图。

车载系统攻城狮 1704

关于用Java刷Leetcode的感想

1.由于Leetcode不需要自己处理输入输出,所以用Java语言时不需要关注输入输出的问题,这是很好的。事实上,对于开发而言,输入输出也不是很重要。 2. Java语言有很多集合框架可以直接用,是很好的。但是API比较多,对象都需要new,需要借助IDE 3. Java的字符串是不可变的,需要借助stringbulider或者字符数组 4.总体而言,Java语言写出来比较规范,显得工程化,不像有些C++写的很随意。 ...

wwxy1995的博客 1689

基于MATLAB的脑功能网络工具箱:BCT与FCLab

脑功能网络分析是神经科学领域的一个重要研究方向,它通过分析大脑中神经元之间的连接模式和信息传递方式,揭示脑网络的结构和功能。在这个领域,MATLAB是一个广泛使用的工具,提供了丰富的函数和工具箱来进行脑功能网络的分析和可视化。这些工具箱提供了丰富的函数和工具,使得脑功能网络的计算和分析变得更加简单和高效。在上述示例代码中,我们首先导入BCT工具箱,并构建一个邻接矩阵来表示脑网络的连接关系。在上述示例代码中,我们首先导入FCLab工具箱,并导入脑功能数据。函数对数据进行预处理,如去除噪声、降采样等操作。

web_bug407的博客 2611

关务管理项目专题:SAP 与关衡关务系统的进出口报关业务集成(1)需求和方案整理

一个拥有进出口业务的企业就需要报关,而关务系统就是用来辅助企业日常进出口报关,同时数字化、合规化报关业务的有效工具。本章属于关务管理项目专题系列,以 SAP 与关衡关务系统的进出口报关业务集成为实例,详细讲解报关业务的需求和方案整理。

SAP李斌,本人承诺所有原创文章均不使用任何AI生成技术,请大家放心阅读。 2080

LeetCode之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. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2.

码莎拉蒂 2135

循环神经网络(RNN)原理及BPTT算法

因循环神经网络基于ANN之上,理解ANN有助于理解RNN,所以阅读此文,建议先阅读。

L 1769

LeetCode387—First Unique Character in a String

LeetCode387 First Unique Character in A String

上善若水 1865

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

关于LeetCode中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.

zsy112371的专栏 536

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

【java学习记录】Java实现leetcode题目 First Unique Character in a String

问题描述:对于任意一个由字母组成的字符串,返回字符串中第一个非重复字符的位置;如果不存在非重复字符则返回-1。例如给出 s = 'leetcode' 返回 0,给出s = 'loveleetcode' 返回 2。对此设计一个算法,其中心思想是建立一快一慢两个指针对字符串进行扫描,慢指针为当前考察字符串,快指针用于检测慢指针后是否有字符与慢指针相同。如果检测到了重复字符,则将该字符加入重复字符集中,...

weixin_40829634的博客 182

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

First Unique Character in a String

From LeetCode No.387; Tier:Easy Content: 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 = “...

sinat_38486956的博客 165

【Leetcode】387. First Unique Character in a String

题目地址: https://leetcode.com/problems/first-unique-character-in-a-string/ 给定一个字符串,找最先出现的整个字符串中只出现一次的字符。如果不存在则返回−1-1−1。代码如下: import java.util.HashMap; import java.util.Map; public class Solution { p...

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

【LeetCode & 剑指offer刷题】字符串题1:50 第一个只出现一次的字符(387. First Unique Character in a String)...

【LeetCode &amp; 剑指offer刷题】字符串题1:50 第一个只出现一次的字符(387. First Unique Character in a String) 【LeetCode &amp; 剑指offer 刷题笔记】目录(持续更新中...) 387. First Unique Character in a String G...

技术改变世界 1182

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

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

Minecraft 2363

leetcode 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. 中文理解:给出...

leo_weile的博客 217

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:

淡然坊 341

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

(ÒωÓױ) 2240

【LeetCode】387 First Unique Character in a String(java实现)

原题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 may assume t

添经地翼的博客 2744

LeetCode 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" retu

雪水 573

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

不思量 178
上一篇: LeetCode算法题-Ransom Note(Java实现)
下一篇: LeetCode算法题-Find the Difference(Java实现-五种解法)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值