字符串中的第一个唯一字符

387. 字符串中的第一个唯一字符

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

 

示例 1:

输入: s = "leetcode"
输出: 0

示例 2:

输入: s = "loveleetcode"
输出: 2

示例 3:

输入: s = "aabb"
输出: -1

 

提示:

  • 1 <= s.length <= 105
  • s 只包含小写字母
复制代码
 1 #include <iostream>
 2 #include <string>
 3 #include <unordered_map>
 4 
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     int firstUniqChar(string s) {
10         // key->字符, value->字字符出现次数
11         unordered_map<char, int> m; 
12         for (const auto &ch : s) {
13             m[ch]++;
14         }
15         int index = 0;
16         for (const auto &ch : s) {
17             if (m[ch] == 1) {
18                 return index;
19             }
20             index++;
21         }
22         return -1;
23     }
24 };
25 
26 int main()
27 {
28     Solution *test = new Solution();
29     std::string s = "leetcode";
30     std::cout << test->firstUniqChar(s) << endl; // 0
31     s = "loveleetcode";
32     std::cout << test->firstUniqChar(s) << endl; // 2
33     s = "aabb";
34     std::cout << test->firstUniqChar(s) << endl; // -1
35     delete test;
36     system("pause");
37     return 0;
38 }
复制代码

运行效果:

 

 

posted @   跳动的休止符  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示