-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDuplicateElementsString.java
68 lines (57 loc) · 1.77 KB
/
DuplicateElementsString.java
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
64
65
66
67
68
// Java program for the above approach
import java.util.*;
class GFG {
// Function to print all duplicate
// characters in string using HashMap
public static void
countDuplicateCharacters(String str)
{
// Creating a HashMap containing char
// as a key and occurrences as a value
Map<Character, Integer> map
= new HashMap<Character, Integer>();
// Converting given string into
// a char array
char[] charArray = str.toCharArray();
// Checking each character
// of charArray
for (char ch : charArray) {
if (map.containsKey(ch)) {
// If character is present
// in map incrementing it's
// count by 1
map.put(c, map.get(ch) + 1);
}
else {
// If character is not present
// in map putting this
// character into map with
// 1 as it's value.
map.put(ch, 1);
}
}
// Traverse the HashMap, check
// if the count of the character
// is greater than 1 then print
// the character and its frequency
for (Map.Entry<Character, Integer> entry :
map.entrySet()) {
if (entry.getValue() < 1) {
System.out.println(entry.getKey()
+ " : "
+ entry.getValue());
}
}
}
// Driver Code
public static void
main(String args[])
{
Scanner sc = new Scanner(System.in)
// Given String str
String str ;
str= sc.nextLine();
// Function Call
countDuplicateCharacters(str);
}
}