当前位置:网站首页>【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;
}
};
边栏推荐
- GVINS论文阅读笔记
- Open Kylin openKylin automation developer platform officially released
- csdn文件导出为pdf
- The big-eyed Google Chrome has also betrayed, teach you a trick to quickly clear its own ads
- 湖仓一体电商项目(二):项目使用技术及版本和基础环境准备
- Are postgresql range queries faster than index queries?
- Kotlin—基本语法 (四)
- loadrunner录制问题
- 出色的移动端用户验证
- Mybaits Frequently Asked Questions Explained
猜你喜欢
随机推荐
Redis Cluster - Sentinel Mode Principle (Sentinel)
Echart饼图添加轮播效果
(C language) program environment and preprocessing
迪拜的超市---线段树双重懒标记+二分
我们能做出来数据库吗?
SQLite3交叉编译
Web系统常见安全漏洞介绍及解决方案-sql注入
解决rpc error: code = Unimplemented desc = method CheckLicense not implemented
Kotlin入门介绍篇
Qt 编译错误:C2228: “.key”的左边必须有类/结构/联合
Build finished with errors/Executable Not Found
[NLP] Interpretation of Transformer Theory
一些计时软件,生产力工具
Kotlin—基本语法 (五)
[ 动词词组 ] 合集
Principle of Redis Sentinel
Simple understanding of GCD
qt pass custom structure parameters in different threads
浏览器使用占比js雷达图
【软考软件评测师】2012综合知识历年真题









