-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0387.java
More file actions
42 lines (33 loc) · 1.14 KB
/
_0387.java
File metadata and controls
42 lines (33 loc) · 1.14 KB
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
package com.github.aditya;
import java.util.HashMap;
import java.util.Map;
public class _0387 {
// Better Solution, 1 ms, faster than 100.00% Using String
class Solution {
public int firstUniqChar(String s) {
int min = Integer.MAX_VALUE;
for (char i = 'a'; i <= 'z'; i++) {
int index = s.indexOf(i);
if (index != -1 && index == s.lastIndexOf(i))
min = Math.min(min, index);
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
// Expensive Solution using HashMap, Looping Twice
class Solution_1 {
public int firstUniqChar(String s) {
Map<Character, Integer> countMap = new HashMap();
for (char ch : s.toCharArray()) {
countMap.put(ch, countMap.getOrDefault(ch, 0) + 1);
}
int min = Integer.MAX_VALUE;
for (char ch : countMap.keySet()) {
if (countMap.get(ch) == 1) {
min = Math.min(s.indexOf(ch), min);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
}