LeetCode刷题(16)~字符串中的第一个唯一字符
【摘要】 题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
12345
解答 By 海轰
提交代码
class Solution {
public: int firstUniqChar(string s) {
int len...
题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
- 1
- 2
- 3
- 4
- 5
解答 By 海轰
提交代码
class Solution {
public: int firstUniqChar(string s) {
int len=s.size();
if(len<=1) return len-1;
unordered_map<char,int> m;
for(int i=0;i<len;++i)
++m[s[i]];
for(int i=0;i<len;++i)
if(m[s[i]]==1)
return i;
return -1; }
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
运行结果

思路
先将所有的字符压入哈希表中,统计出现个数,然后再遍历strng字符串,如果遇到次数为1,则return 当前下标。
这里可以稍微优化一下,就是利用数组代替map,这样可以节约一点内存和时间。
C++完整测试代码
#include <iostream>
#include <iterator>
#include <unordered_map>
using namespace std;
// 方法一
int firstUniqChar_1(string s)
{ int len = s.size(); if (len <= 1) return len - 1; unordered_map<char, int> m; for (int i = 0; i < len; ++i) ++m[s[i]]; for (int i = 0; i < len; ++i) if (m[s[i]] == 1) return i; return -1;
}
// 方法二
int firstUniqChar_2(string s)
{ int arr[26]; memset(arr, 0, sizeof(arr)); for (auto c : s) arr[c - 'a']++; for (int i = 0; i < s.length(); i++) if (arr[s[i] - 'a'] == 1) return i; return -1;
}
int main()
{ string a = "leetcode"; cout << firstUniqChar_1(a) << endl; return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
文章来源: haihong.blog.csdn.net,作者:海轰Pro,版权归原作者所有,如需转载,请联系作者。
原文链接:haihong.blog.csdn.net/article/details/107817207
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)