-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicateCharacters.java
More file actions
29 lines (26 loc) · 1021 Bytes
/
DuplicateCharacters.java
File metadata and controls
29 lines (26 loc) · 1021 Bytes
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
// 45. Write a program to find and display duplicate characters in a string.
import java.util.HashMap;
import java.util.Map;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
findDuplicateCharacters(str);
}
public static void findDuplicateCharacters(String str) {
Map<Character, Integer> charCountMap = new HashMap<>();
char[] chars = str.toCharArray();
for (char ch : chars) {
if (charCountMap.containsKey(ch)) {
charCountMap.put(ch, charCountMap.get(ch) + 1);
} else {
charCountMap.put(ch, 1);
}
}
System.out.println("Duplicate characters in the string:");
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " - " + entry.getValue() + " times");
}
}
}
}