387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
문자열에 나오는 알파벳의 갯수를 배열에 저장한다.
문자열을 하나씩 돌면서 이전에 저장한 문자열의 갯수를 비교하며 1인 경우에는 문자의 인덱스를 반환하고, 갯수가 1인 문자를 찾지 못하면 -1을 반환한다.
class Solution {
public:
int firstUniqChar(string s) {
int alphabet[26] = { 0 };
for (int i = 0; i < s.size(); i++) {
alphabet[s[i] - 'a']++;
}
for (int i = 0; i < s.size(); i++) {
if (alphabet[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
};