-
Notifications
You must be signed in to change notification settings - Fork 0
/
387. First Unique Character
48 lines (34 loc) · 1.08 KB
/
387. First Unique Character
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
44
45
46
47
48
/* 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.
Note: You may assume the string contains only lowercase English letters.
Question link: https://leetcode.com/problems/first-unique-character-in-a-string/
*/
----------------------------------------------------------
Code:
class Solution {
public int firstUniqChar(String s) {
if(s.length() == 0){
return -1;
}
HashMap<Character, Integer> map = new HashMap<Character,Integer>();
int ans = -1;
for(int i = 0; i<s.length(); i++){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
}else{
map.put(s.charAt(i), 1);
}
}
for(int i = 0; i<s.length(); i++){
if(map.get(s.charAt(i)) == 1){
ans = i;
break;
}
}
return ans;
}
}