0%

Leetcode387-firstUniqueCharacterInAString

Description

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

Example

1
2
3
4
5
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) return -1;

HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++){
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < s.length(); i++){
if (map.get(s.charAt(i)) == 1) return i;
}
return -1;
}
}

Method 2: More faster

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int firstUniqChar(String s) {
if (s.length() == 0) return -1;

int[] countRepeats = new int[128];
for(int i=0; i<s.length(); i++){
countRepeats[s.charAt(i)]++;
}
for(int i=0; i<s.length(); i++){
if(countRepeats[s.charAt(i)] == 1)
return i;
}
return -1;
}
}