[leetcode] problem 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

No.1

s = “leetcode”
return 0.

No.2

s = “loveleetcode”,
return 2.

Note

You may assume the string contain only lowercase letters.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int (String s) {
if (s == null || s.length() < 1)
return -1;

int[] index = new int[26];

for (int i = 0; i < s.length(); i++) {
int idx = s.charAt(i) - 'a';
index[idx]++;
}

for (int i = 0; i < s.length(); i++) {
int idx = s.charAt(i) - 'a';

if (index[idx] == 1)
return i;
}

return -1;
}