当前位置:网站首页>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
};
边栏推荐
- Chrome浏览器的crash问题
- 延迟初始化和密封类
- Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
- Screenshot in win10 system, win+prtsc save location
- C语言深度解剖——C语言关键字
- JS inheritance method
- Light of domestic games destroyed by cracking
- Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
- 生成器参数传入参数
- C語言雙指針——經典題型
猜你喜欢

TP-LINK enterprise router PPTP configuration

ROS编译 调用第三方动态库(xxx.so)

Deep learning: derivation of shallow neural networks and deep neural networks

2022.02.13 - 238. Maximum number of "balloons"

游戏解包的危害及资源加密的重要性

企微服务商平台收费接口对接教程

Image, CV2 read the conversion and size resize change of numpy array of pictures

UnsupportedOperationException异常

Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines

Deep analysis of C language data storage in memory
随机推荐
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
【刷题】牛客网面试必刷TOP101
Esp8266-rtos IOT development
egg. JS directory structure
swagger设置字段required必填
角色动画(Character Animation)的现状与趋势
Roguelike game into crack the hardest hit areas, how to break the bureau?
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
生成器参数传入参数
Navicat Premium 创建MySql 创建存储过程
Detailed explanation of heap sorting
Indentation of tabs and spaces when writing programs for sublime text
【MySQL】锁
sublime text中conda环境中plt.show无法弹出显示图片的问题
ROS compilation calls the third-party dynamic library (xxx.so)
Golang force buckle leetcode 1020 Number of enclaves
Unsupported operation exception
C language double pointer -- classic question type
个人电脑好用必备软件(使用过)
深度剖析C语言数据在内存中的存储