当前位置:网站首页>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
};
边栏推荐
- Compétences en mémoire des graphiques UML
- Introduction to the differences between compiler options of GCC dynamic library FPIC and FPIC
- LeetCode:236. 二叉树的最近公共祖先
- Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
- Trying to use is on a network resource that is unavailable
- The mysqlbinlog command uses
- 多元聚类分析
- Current situation and trend of character animation
- 有效提高软件产品质量,就找第三方软件测评机构
- How to conduct interface test? What are the precautions? Nanny level interpretation
猜你喜欢
Visual implementation and inspection of visdom
Mobile phones and computers on the same LAN access each other, IIS settings
opencv+dlib实现给蒙娜丽莎“配”眼镜
[sword finger offer] serialized binary tree
ant-design的走马灯(Carousel)组件在TS(typescript)环境中调用prev以及next方法
可变长参数
[embedded] cortex m4f DSP Library
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
Generator parameters incoming parameters
Nacos 的安装与服务的注册
随机推荐
软件压力测试常见流程有哪些?专业出具软件测试报告公司分享
Hutool gracefully parses URL links and obtains parameters
Detailed explanation of dynamic planning
生成器参数传入参数
Excellent software testers have these abilities
swagger设置字段required必填
Tdengine biweekly selection of community issues | phase III
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
LeetCode:387. 字符串中的第一个唯一字符
Using C language to complete a simple calculator (function pointer array and callback function)
MYSQL卸载方法与安装方法
opencv+dlib实现给蒙娜丽莎“配”眼镜
UML diagram memory skills
LeetCode:剑指 Offer 48. 最长不含重复字符的子字符串
企微服务商平台收费接口对接教程
POI add write excel file
Deep anatomy of C language -- C language keywords
After reading the programmer's story, I can't help covering my chest...
pytorch训练好的模型在加载和保存过程中的问题
Simple use of promise in uniapp