-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonRepeatedChar.java
More file actions
63 lines (52 loc) · 1.13 KB
/
NonRepeatedChar.java
File metadata and controls
63 lines (52 loc) · 1.13 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
54
55
56
57
58
59
60
61
62
63
import java.util.HashMap;
import java.util.Map;
/**
* * Find first non-repeating character
* * @author hduser
* *
* */
public class NonRepeatedChar {
/**
* * Naive solution O(n^2) is to get one element and
* * re-scan whole elements.
* */
/**
* * Complexity : Time = O(n)
* * @param str
* * @return
* */
public char findFirstNonRepeatedChar(String str) {
Map<Character,Integer> countMap = new HashMap<Complexityharacter, Integer>();
char[] chArr = str.toCharArray();
/**
* *new Traverse once
* */
for (char ch:chArr) {
if (countMap.containsKey(ch)) {
int val = countMap.get(ch);
val += 1;
countMap.put(ch, val);
} else {
countMap.put(ch, 1);
}
}
/**
* * 2nd traversal to identify first non-repeating character
* */
for (char ch:chArr) {
if (countMap.get(ch) == 1) {
return ch;
}
}
return 0;
}
public static void main() {
NonRepeatedChar non = new NonRepeatedChar();
char ch = non.findFirstNonRepeatedChar("RamSRhyam");
if(ch == 0) {
System.out.println("char not found");
} else {
System.out.println("char Found "+ ch);
}
}
}