当前位置:网站首页>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
};
边栏推荐
- Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
- Unified ordering background interface product description Chinese garbled
- 同一局域网的手机和电脑相互访问,IIS设置
- Problems in loading and saving pytorch trained models
- sublime text的编写程序时的Tab和空格缩进问题
- 【MySQL】锁
- 如何进行接口测试测?有哪些注意事项?保姆级解读
- [embedded] cortex m4f DSP Library
- Is it safe to open an account in Zheshang futures?
- China vanadium battery Market Research and future prospects report (2022 Edition)
猜你喜欢
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
角色动画(Character Animation)的现状与趋势
MySQL learning record 10getting started with JDBC
Tcp/ip protocol
Image, CV2 read the conversion and size resize change of numpy array of pictures
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
深度剖析C语言指针
Navicat Premium 创建MySql 创建存储过程
延迟初始化和密封类
随机推荐
Swagger setting field required is mandatory
Cisp-pte practice explanation
同一局域网的手机和电脑相互访问,IIS设置
Shift Operators
Visual implementation and inspection of visdom
TDengine 社区问题双周精选 | 第三期
个人电脑好用必备软件(使用过)
JS native implementation shuttle box
Light of domestic games destroyed by cracking
Unsupported operation exception
marathon-envs项目环境配置(强化学习模仿参考动作)
egg. JS getting started navigation: installation, use and learning
Crash problem of Chrome browser
MySQL learning record 07 index (simple understanding)
2022.02.13 - NC003. Design LRU cache structure
What is CSRF (Cross Site Request Forgery)?
如何有效地进行自动化测试?
pytorch训练好的模型在加载和保存过程中的问题
Roguelike游戏成破解重灾区,如何破局?
软件压力测试常见流程有哪些?专业出具软件测试报告公司分享