当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
浏览器使用占比js雷达图
【TCP/IP】Network Model
Web系统常见安全漏洞介绍及解决方案-sql注入
Redis集群-哨兵模式原理(Sentinel)
如何在 TiDB Cloud 上使用 Databricks 进行数据分析 | TiDB Cloud 使用指南
开放麒麟 openKylin 自动化开发者平台正式发布
第二十三课,抗锯齿(Anti Aliasing)
Mybaits Frequently Asked Questions Explained
Gradle series - Groovy overview, basic use (based on Groovy document 4.0.4) day2-1
Redis Sentinel原理
随机推荐
Kotlin入门介绍篇
如何将亚马逊广告添加到您的 WordPress 网站(3 种方法)
loadrunner-controller-view script与load generator
混合型界面:对话式UI的未来
如何判断自己是否适合IT行业?方法很简单
使用turtle画按钮
GVINS论文阅读笔记
postgresql 范围查询比索引查询快吗?
零代码工具推荐 八爪鱼采集器
Day113. Shangyitong: user authentication, Alibaba Cloud OSS, patient management
Gradle series - Groovy overview, basic use (based on Groovy document 4.0.4) day2-1
NowCoderTOP28-34 binary tree - continuous update ing
Qt compile error: C2228: '.key' must have class/struct/union on the left
Mybaits Frequently Asked Questions Explained
ReentrantLock
Kotlin—基本语法(二)
[ 动词词组 ] 合集
来n遍剑指--07. 重建二叉树
The future of the hybrid interface: conversational UI
Centos7 install mysql5.7