-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirstUniqueChar.h
43 lines (41 loc) · 1.06 KB
/
firstUniqueChar.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//
// Created by so_go on 2019/5/27.
//
#ifndef SRC_FIRSTUNIQUECHAR_H
#define SRC_FIRSTUNIQUECHAR_H
#include<string>
#include<array>
#include<limits>
using namespace std;
class FirstUniqChar {
public:
// 记录第一次出现位置 数组, 记录出现次数
int firstUniqChar(string s) {
array<int ,26> count;
array<int, 26> first_apr;
count.fill(0);
first_apr.fill(-1);
int ord;
for(int i = 0; i < s.size(); ++i){
ord = s[i] - 'a';
count[ord] += 1;
if( first_apr[ord] == -1){
first_apr[ord] = i;
}
}
int min_pos = s.size();
for(int j = 0; j < 26; ++j){
if(count[j] == 1){
if(first_apr[j] < min_pos){
// cout << j << ' ' << first_apr[j] << ' ' << min_pos << endl;
min_pos = first_apr[j];
}
}
}
if(min_pos == s.size())
return -1;
else
return min_pos;
}
};
#endif //SRC_FIRSTUNIQUECHAR_H