当前位置:网站首页>LeetCode:387. The first unique character in the string
LeetCode:387. The first unique character in the string
2022-07-06 08:51:00 【Bertil】
Given a string s , find Its first non repeating character , And return its index . If it doesn't exist , Then return to -1 .
Example 1:
Input : s = "leetcode"
Output : 0
Example 2:
Input : s = "loveleetcode"
Output : 2
Example 3:
Input : s = "aabb"
Output : -1
Tips :
- 1 <= s.length <= 10^5
- s Contains only lowercase letters
Their thinking
1. First, use a hash table to count the number of times each letter appears
2. Then iterate through the string , If a character is found to appear only once , Directly return the corresponding subscript , Otherwise, return after the loop ends -1
Code
/** * @param {string} s * @return {number} */
var firstUniqChar = function(s) {
// Create a hash table
let map = new Map()
// Count the times
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)
}
}
// Find the first letter that appears only once
for (let i = 0; i < s.length; i++) {
if (map.get(s.charAt(i)) === 1) {
return i
}
}
return -1
};
边栏推荐
- Screenshot in win10 system, win+prtsc save location
- LeetCode:387. 字符串中的第一个唯一字符
- ESP8266-RTOS物联网开发
- 【嵌入式】Cortex M4F DSP库
- [sword finger offer] serialized binary tree
- POI add write excel file
- TCP/IP协议
- sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
- MySQL uninstallation and installation methods
- Restful API design specification
猜你喜欢

JVM quick start

ROS compilation calls the third-party dynamic library (xxx.so)

Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)

Nacos 的安装与服务的注册

SAP ui5 date type sap ui. model. type. Analysis of the parsing format of date

项目连接数据库遇到的问题及解决

704 binary search

C语言双指针——经典题型

MySQL uninstallation and installation methods

Warning in install. packages : package ‘RGtk2’ is not available for this version of R
随机推荐
Sublime text using ctrl+b to run another program without closing other runs
TP-LINK enterprise router PPTP configuration
角色动画(Character Animation)的现状与趋势
Using C language to complete a simple calculator (function pointer array and callback function)
LeetCode:387. 字符串中的第一个唯一字符
LeetCode:26. 删除有序数组中的重复项
LeetCode:劍指 Offer 42. 連續子數組的最大和
Purpose of computer F1-F12
深度剖析C语言指针
Promise 在uniapp的简单使用
查看局域网中电脑设备
opencv+dlib实现给蒙娜丽莎“配”眼镜
C語言雙指針——經典題型
visdom可视化实现与检查介绍
可变长参数
超高效!Swagger-Yapi的秘密
After reading the programmer's story, I can't help covering my chest...
电脑F1-F12用途
Compétences en mémoire des graphiques UML
LeetCode:394. 字符串解码