-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstNonRepeatChars.java
More file actions
53 lines (40 loc) · 1.31 KB
/
Copy pathFirstNonRepeatChars.java
File metadata and controls
53 lines (40 loc) · 1.31 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
/* Find first non-repeated characters in given String */
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class FirstNonRepeatChars {
public static void main(String[] args) {
String input = "AABDBCCSDM";
// First Approach without Collection
for(int i=0; i<input.length(); i++) {
boolean unique = true;
for(int j=0; j<input.length(); j++) {
if(i!=j && input.charAt(i) == input.charAt(j)) {
unique = false;
break;
}
}
if(unique) {
System.out.println(input.charAt(i));
break;
}
}
// Second Approach with Collection
Map<Character, Integer> map = new HashMap();
for(int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
if(map.containsKey(ch)) {
map.put(ch, map.get(ch)+1);
}else {
map.put(ch, 1);
}
}
System.out.println(map);
for(Entry<Character, Integer> entrySet : map.entrySet()) {
if(entrySet.getValue() == 1) {
System.out.println(entrySet.getKey());
break;
}
}
}
}