[LeetCode] First Unique Character in a String

387. First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int firstUniqChar(string s) {
queue<int> q;
int arr[26]{0,};
for(int i = 0; i < s.length(); i++) {
if(++arr[s[i]-'a'] == 1) q.push(i);
}
while(!q.empty()) {
int index = q.front(); q.pop();
if(arr[s[index]-'a'] == 1) return index;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/14/PS/LeetCode/first-unique-character-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.