当前位置:网站首页>LeetCode:387. 字符串中的第一个唯一字符
LeetCode:387. 字符串中的第一个唯一字符
2022-07-06 08:44:00 【Bertil】
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = "leetcode"
输出: 0
示例 2:
输入: s = "loveleetcode"
输出: 2
示例 3:
输入: s = "aabb"
输出: -1
提示:
- 1 <= s.length <= 10^5
- s 只包含小写字母
解题思路
1.首先用哈希表统计每个字母出现的次数
2.然后遍历字符串,如果发现字符只出现一次,直接返回对应的下标,否则循环终止之后返回-1
代码
/** * @param {string} s * @return {number} */
var firstUniqChar = function(s) {
// 创建一个哈希表
let map = new Map()
// 统计次数
for (let i = 0; i < s.length; i++) {
let word = s.charAt(i)
if (map.has(word)) {
let val = map.get(word)
map.set(word, val + 1)
} else {
map.set(word, 1)
}
}
// 找到第一个只出现一次的字母
for (let i = 0; i < s.length; i++) {
if (map.get(s.charAt(i)) === 1) {
return i
}
}
return -1
};
边栏推荐
- Generator parameters incoming parameters
- 被破解毁掉的国产游戏之光
- Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
- JVM performance tuning and practical basic theory - Part 1
- Roguelike game into crack the hardest hit areas, how to break the bureau?
- Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges
- Modify the video name from the name mapping relationship in the table
- 深度剖析C语言指针
- C language double pointer -- classic question type
- egg. JS getting started navigation: installation, use and learning
猜你喜欢

2022.02.13 - NC003. Design LRU cache structure

View computer devices in LAN

TP-LINK enterprise router PPTP configuration

2022.02.13 - NC001. Reverse linked list

pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof

egg. JS getting started navigation: installation, use and learning

Computer cleaning, deleted system files

Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges

TP-LINK 企业路由器 PPTP 配置

visdom可视化实现与检查介绍
随机推荐
Double pointeur en langage C - - modèle classique
vb.net 随窗口改变,缩放控件大小以及保持相对位置
Light of domestic games destroyed by cracking
704 binary search
sublime text中conda环境中plt.show无法弹出显示图片的问题
The network model established by torch is displayed by torch viz
Cisp-pte practice explanation
Detailed explanation of heap sorting
Sort according to a number in a string in a column of CSV file
2022.02.13 - NC004. Print number of loops
Promise 在uniapp的简单使用
[brush questions] top101 must be brushed in the interview of niuke.com
The harm of game unpacking and the importance of resource encryption
Hutool gracefully parses URL links and obtains parameters
How to conduct interface test? What are the precautions? Nanny level interpretation
JVM 快速入门
软件卸载时遇到trying to use is on a network resource that is unavailable
Image, CV2 read the conversion and size resize change of numpy array of pictures
Roguelike game into crack the hardest hit areas, how to break the bureau?
广州推进儿童友好城市建设,将探索学校周边200米设安全区域