InterviewSolution
Saved Bookmarks
| 1. |
Write a program to print all the unique characters in a String. For instance, if the input string is “abcb”, the output will be the characters ‘a’ and ‘c’ as they are unique. The character ‘b’ repeats twice and so it will not be printed. |
|
Answer» We can use a HashSet in order to store the characters of the String. When we arrive at a character in the String, if it is already present in the HashSet, we remove it from the HashSet as that character is not unique. If it is not present inside the HashSet, we add it to it. After traversing the entire string, we print the elements inside the HashMap. Java Code to Print All Unique Characters in a String. import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str = scn.nextLine(); HashSet<Character> unique = new HashSet<>(); for(int i=0;i<str.length();i++) { char ch = str.charAt(i); if(unique.contains(ch) == true) { //this character has already occured unique.remove(ch); } else { unique.add(ch); } } if(unique.size() == 0) { System.out.println("There are no unique characters"); } for(Character ch : unique) { System.out.print(ch + " "); } } } Sample Output Input: abcabOutput: c
|
|