当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
作为面试官,关于线程池的问题我一般这样套路...
Burndown chart of project management tools: Dynamic assessment of team work ability
来n遍剑指--06. 从尾到头打印链表
js实现2020年元旦倒计时公告牌
centos7安装mysql5.7
第二十四课、二十五课,高级光照(blinn),Gamma矫正
js空气质量aqi雷达图分析
loadrunner-controller-手动场景Schedule配置
The future of the hybrid interface: conversational UI
Canvas particles change various shapes js special effects
随机推荐
js部门预算和支出雷达图
混合型界面:对话式UI的未来
Simple understanding of GCD
js radar chart statistical chart plugin
spark过滤器
Redis的简单使用
loadrunner脚本--添加集合点
Qt 编译错误:C2228: “.key”的左边必须有类/结构/联合
Kotlin—基本语法(二)
Come n times - 07. Rebuild the binary tree
如何判断自己是否适合IT行业?方法很简单
小程序如何使用订阅消息(PHP代码+小程序js代码)
来n遍剑指--05. 替换空格
SQLite3交叉编译
Source code analysis of GZIPInputStream class
Chapter Six
第二十三课,抗锯齿(Anti Aliasing)
nodeJs--querystring模块
实现线程池
Kotlin—基本语法(三)