-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDuplicateCharactersInString.java
86 lines (76 loc) · 2.06 KB
/
DuplicateCharactersInString.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.javamultiplex.string;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
/**
*
* @author Rohit Agarwal
* @category String Interview Question
* @Problem Print all duplicate characters in a String
*
*/
public class DuplicateCharactersInString {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter String: ");
String string=input.next();
char[] stringToChar=string.toCharArray(); //Converting String to char Array.
int orignalLength=stringToChar.length,charCount=0;
String newString=getStringAfterDuplicatesRemoval(stringToChar);
char[] stringToCharAfterDuplicateRemoval=newString.toCharArray(); //Converting String to char Array.
int newLength=stringToCharAfterDuplicateRemoval.length;
if(string.equals(newString))
{
System.out.println("No duplicate character available.");
}
else
{
System.out.println("Duplicate characters are: ");
for(int i=0;i<newLength;i++)
{
charCount=0;
for(int j=0;j<orignalLength;j++)
{
if(stringToCharAfterDuplicateRemoval[i]==stringToChar[j])
{
charCount++;
}
}
if(charCount>1)
{
System.out.println(stringToCharAfterDuplicateRemoval[i]);
}
}
}
}
finally
{
if(input!=null)
{
input.close();
}
}
}
/*
* Removing duplicates by converting char Array to Set.
*/
private static String getStringAfterDuplicatesRemoval(char[] stringToChar) {
HashSet<Character> set=new LinkedHashSet<>();
String result="";
int orignalLength=stringToChar.length;
for(int i=0;i<orignalLength;i++)
{
set.add(stringToChar[i]);
}
Iterator<Character> iterator=set.iterator();
while(iterator.hasNext())
{
result+=iterator.next(); //Converting Set to String
}
return result;
}
}