In this question, we have to print duplicate characters i.e. the characters which come more than once in the given string.
ex:-
- java (in "java", 'a' is the only duplicate character as it comes more than once, other than that 'j' and 'v' comes only one time in the given string ).
- python ( in "python" all the characters come only on time so there is no duplicate character in the given string "python").
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Scanner; public class PrintDuplicateCharacters { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String duplicate_str = ""; String str = sc.next(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if ((str.indexOf(c)!= str.lastIndexOf(c)) && !duplicate_str.contains(c + "")) { duplicate_str += c; } } System.out.println(duplicate_str); } } |
Java ( using HashMap )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*;
public class PrintDuplicate{
public static void main(String []args){
String s = "codecheistc" ;
Map<Character,Integer> hm = new HashMap();
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(hm.containsKey(ch))
hm.put(ch, hm.get(ch)+1);
else
hm.put(ch, 1);
}
hm.forEach( (K, V) -> {
if(V>1)
System.out.print(K+" ");
});
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.util.*; public class PrintDuplicate{ public static void main(String []args){ String s = "codecheistc" ; Map<Character,Integer> hm = new HashMap(); for(int i=0; i<s.length(); i++){ char ch = s.charAt(i); if(hm.containsKey(ch)) hm.put(ch, hm.get(ch)+1); else hm.put(ch, 1); } hm.forEach( (K, V) -> { if(V>1) System.out.print(K+" "); }); } } |
Python
input_str = input("Enter String:") duplicate_str = "" for i in range(0,len(input_str)-1): if input_str[i] in input_str[i+1:] and input_str[i] not in duplicate_str: duplicate_str += input_str[i] print(duplicate_str) |