387. First Unique Character in a String - LeetCode

387. First Unique Character in a String

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

Examples:

s = “leetcode”
return 0.

s = “loveleetcode”,
return 2.

Note: You may assume the string contain only lowercase letters.

Solution:

因为不到最后无法得知出现是否重复, 于是建立一个Hash表,大小为26个lower字母, 存放每个字符出现的次数.

// Time:O(n), Space:O(1)
class Solution {
public:
int firstUniqChar(string s) {
int cnt[30];
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i < s.length(); i++) {
cnt[s[i] - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (cnt[s[i] - 'a'] == 1) return i;
}
return -1;
}
};