当前位置:网站首页>【LeetCode】387. 字符串中的第一个唯一字符
【LeetCode】387. 字符串中的第一个唯一字符
2022-07-31 10:03:00 【酥酥~】
题目
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = “leetcode”
输出: 0
示例 2:
输入: s = “loveleetcode”
输出: 2
示例 3:
输入: s = “aabb”
输出: -1
提示:
1 <= s.length <= 105
s 只包含小写字母
题解
使用哈希表存储字符频率
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<int,int> mystrs;
int len = s.length();
for(int i=0;i<len;i++)//第一遍循环存储频率
{
mystrs[s[i]]++;
}
for(int i=0;i<len;i++)//第二遍循环寻找第一个唯一字符
{
if(mystrs[s[i]] == 1)
return i;
}
return -1;
}
};
用哈希表存储下标
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char,int> mystrs;
int len = s.length();
for(int i=0;i<len;i++)//第一遍遍历存储下标
{
if(mystrs.count(s[i]))//如果已经存在,则标为-1
mystrs[s[i]] = -1;
else
mystrs[s[i]] = i;
}
int result = len;
for(auto [_,index]:mystrs)//寻找不重复字符最小下标
{
if(index!=-1 && index<result)
result = index;
}
if(result==len)
return -1;
else
return result;
}
};
边栏推荐
猜你喜欢
随机推荐
Data Middle Office Construction (6): Data System Construction
NowCoderTOP28-34二叉树——持续更新ing
loadrunner-Controller负载测试-各模块功能记录01测试场景设计
【GORM】存取数组/自定义类型数据
js department budget and expenditure radar chart
Meikle Studio--Hongmeng 14-day development training notes (8)
Gradle series - Groovy overview, basic use (based on Groovy document 4.0.4) day2-1
The future of the hybrid interface: conversational UI
js实现2020年元旦倒计时公告牌
感情危机,朋友的网恋女友要和他闹分手,问我怎么办
js implements the 2020 New Year's Day countdown bulletin board
如何判断自己是否适合IT行业?方法很简单
[ 动词词组 ] 合集
nodeJs--url模块
Open Kylin openKylin automation developer platform officially released
Android安全专题(三)JNI混淆
Kotlin入门介绍篇
ARC在编译和运行做了什么?
&#x开头的是什么编码?
Centos7 install mysql5.7









