-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP39_FirstNonRepeatedChar.java
More file actions
42 lines (35 loc) · 1.37 KB
/
Copy pathP39_FirstNonRepeatedChar.java
File metadata and controls
42 lines (35 loc) · 1.37 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 programs;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* ============================================================
* PROGRAM 39: Find First Non-Repeated Character in String
* ============================================================
* Problem: WAP to find the first character in a string that does not repeat.
* - Input : "swiss" -> Output: 'w'
* - Input : "teeter" -> Output: 'r'
* ============================================================
*/
public class P39_FirstNonRepeatedChar {
public static Character findFirstNonRepeated(String str) {
if (str == null || str.isEmpty()) return null;
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
counts.put(c, counts.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return null; // All repeat
}
public static void main(String[] args) {
String[] samples = {"swiss", "teeter", "aabbcc", "antigravity"};
for (String s : samples) {
Character c = findFirstNonRepeated(s);
System.out.printf(" \"%-12s\" -> First Non-repeated: %s%n",
s, (c == null ? "None" : "'" + c + "'"));
}
}
}