LeetCode387 First Unique Character in a String

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

样例

1
2
3
4
5
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

思路

找出在字符串中只出现过一次的字符的下标。

水题…统计一遍即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int firstUniqChar(string s) {
int cnt[26] = {0}, i = 0, ans = -1;
for (char c: s) cnt[c-'a']++;
for (char c: s) {
if (cnt[c-'a'] == 1) {
ans = i;
break;
}
i++;
}
return ans;
}
};
分享到 评论