当前位置:网站首页>力扣每日一题-第52天-387. 字符串中的第一个唯一字符
力扣每日一题-第52天-387. 字符串中的第一个唯一字符
2022-08-10 23:44:00 【重邮研究森】
2022.8.10今天你刷题了吗?
题目:
给定一个字符串 s
,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1
。
分析:
给你一个字符串,你需要找出没有重复的字母,然后返回一个下标最小的字母的下标是多少。
思路:对于重复直接哈希,先把所有元素插入哈希表中,可以得到每个元素的重复次数。接着遍历这个哈希,找到次数为1的第一个元素。注意,在第二次遍历的时候,我们是按字符串下标开始遍历,举个例子
for(int i=0;i<s.size();i++)
那么在i=0时,我们需要判断s【i】在哈希中的次数是否为1,如果不是,则下一个。
那么在i=1时,我们又判断次数是否为1,如果是则直接返回下标。
解析:
1.哈希表
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int>map;
for (auto num : s)
{
map[num]++;
}
for (int i = 0; i < s.size(); i++)
{
if (map[s[i]] == 1)
{
return i;
}
}
return -1;
}
};
2.哈希映射
这里的区别在于,哈希表存放的元素为(元素,下标),但次数只有-1和下标.对于重复元素直接给-1.然后下一个遍历就直接遍历次数为1的哈希表,并且判断谁的下标最小就是谁
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int>map;
for (int i = 0; i < s.size(); i++)
{
if (map.count(s[i]))
{
map[s[i]] = -1;
}
else
{
map[s[i]] = i;
}
}
int first = s.size();
for (auto num : map)
{
if (num.second != -1 && num.second < first)
{
first = num.second;
}
}
if (first == s.size())
{
return -1;
}
return first;
}
};
边栏推荐
猜你喜欢
CW614N铜棒CuZn39Pb3对应牌号
2. 依赖管理和自动配置
12. Handling JSON
[C] the C language program design, dynamic address book (order)
特殊类与类型转换
Parse method's parameter list (including parameter names)
服务器小常识
关于弱监督学习的详细介绍——A Brief Introduction to Weakly Supervised Learning
9. Rest 风格请求处理
[C language] Detailed explanation of data storage
随机推荐
《剑指offer》题解——week2(持续更新)
Microsoft: Into Focus with Scott Guthrie Scott Hanselman Rajesh Jha and Kevin Scott | KEY11
[C language] First understanding of pointers
What is the ASIO4ALL
CF1286E-Fedya the Potter Strikes Back【KMP,RMQ】
缓存知识总结
jsp中使用JDBC连接mysql的方法与实例
CW617N锡青铜 CuZn40Pb2对应牌号
Geogebra 教程之 02 Geogebra初学者的 8 个基本要素
Design and Realization of Employment Management System in Colleges and Universities
Easy-to-use translation plug-in - one-click automatic translation plug-in software
如何做专利挖掘,关键是寻找专利点,其实并不太难
UOJ#749-[UNR #6]稳健型选手【贪心,分治,主席树】
HGAME 2022 Week1 writeup
【C语言】C语言程序设计:动态通讯录(顺序表实现)
Geogebra 教程之 03 没有铅笔的数学
[C] the C language program design, dynamic address book (order)
Talking about cors
[C language] binary search (half search)
Three-column layout implementation