-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFirstNonRepeatingCharacter.java
More file actions
53 lines (41 loc) · 1.29 KB
/
Copy pathFirstNonRepeatingCharacter.java
File metadata and controls
53 lines (41 loc) · 1.29 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
43
44
45
46
47
48
49
50
51
52
53
package questions.codesignal.firstnonrepeatingcharacter;
public class FirstNonRepeatingCharacter {
// O(2n) time ~ O(n) time
public static char firstNotRepeatingCharacter(String s) {
// HashMap<Character, Integer> counts = new HashMap<>();
//
// for (int i = 0; i < s.length(); i++) {
// char c = s.charAt(i);
//
// if (counts.containsKey(c)) {
// counts.put(c, counts.get(c) + 1);
// } else {
// counts.put(c, 1);
// }
// }
//
// for (int i = 0; i < s.length(); i++) {
// char c = s.charAt(i);
//
// if (counts.get(c) == 1) {
// return c;
// }
// }
int[] counts = new int[26]; // create 26 alphabet index
for (char c: s.toCharArray()) {
counts[c - 'a']++; // ASCII subtraction e.g. 'a' - 'a' is 0 index
}
for (char c: s.toCharArray()) {
if (counts[c - 'a'] == 1) {
return c;
}
}
return '_';
}
public static void main(String[] args) {
String s1 = "abacabad";
System.out.println(firstNotRepeatingCharacter(s1));
String s2 = "abacabaabacaba";
System.out.println(firstNotRepeatingCharacter(s2));
}
}