I have to write a program that counts the uniques characters in a String given by the user. For example \"abc\" returns 3 and \"aabbccd\" returns 4. I am not allow to use advan
Unique Characters In A String:
This is a basic Java interview subject, where the interviewer wants to check the knowledge
of HashSet or indexOf(in case of Java 7) .
Let's take up a question.
Let's say the interview tells you to
Check if the String is unique :
HashSet ensures uniqueness ,In other words , every object in the HashSet presents only once.
Hence, we will use HashSet.
import java.util.HashSet;
import java.util.Set;
public class Abc {
public static void main(String[] args) {
String a = "Gini";
String aa = a.toLowerCase();
if( isUnique(aa) ) {
System.out.println("All characters are unique");
}else {
System.out.println("All characters are not unique");
}
}
public static boolean isUnique(String a ) {
Set< Character> set = new HashSet<>();
char[] charArray =a.toCharArray();
for(Character ch :charArray) {
if(!set.add(ch)) {
return false;
}//if
}//foreach
return true;
}
}
The output in case of GINI will be : All characters are not unique
Now, the count of the unique characters. Here also we will use HashSet because of the uniqueness.
import java.util.HashSet;
public class practice11 {
public static void main(String[] args) {
String a = "Gini";
String aa = a.toLowerCase();
System.out.println(countUniqueCharacters(aa));
}
public static int countUniqueCharacters(String a) {
char[] charArray = a.toCharArray();
HashSet set = new HashSet();
for(int i = 0 ; i< charArray.length ; i++) {
set.add(charArray[i]);
}//for
return set.size() ;//This will give 3
}
}
The output for Gini will be 3 (Gin will be considered) .
indexOf Method : indexOf() returns the index of first occurrence of the character and then we are comparing with -1.
public class Abc {
public static void main(String[] args) {
String a = "Gini";
String aa = a.toLowerCase();
String t = " ";
for (int i = 0; i < aa.length(); i++) {
int pp = aa.charAt(i) ;
if(t.indexOf(aa.charAt(i)) == -1 ) {
t = t + aa.charAt(i);
}//if
}//for
System.out.println(t );// This will give => gin
System.out.println(t.length()); // this will give 3
}//main
}//end
In Java 8, this is extremely easy. We just have to use chars().distinct().count(). But the return type will be long.
class Abc{
public static void main(String[] args) {
String a = "Gini";
String aa = a.toLowerCase();
System.out.println( countUnique(aa));
}
private static long countUnique(String aa) {
// this will give 3(gin. another i will be not be counted as we have used distinct())
return aa.chars().distinct().count() ;
}
}
Another classic Interview Question : Find the First non repeating character in the String OR the First Unique Character in a String. This problem can be solved using the knowledge of HashMap.
class Abc{
public static void main(String[] args) {
String a = "GinaRani" ;
// Output will be G
System.out.println( firstNonRepeatingCharacter(a) );
}//main
public static Character firstNonRepeatingCharacter(String a){
Map map = new HashMap<>();
char[] charArray = a.toCharArray();
for( Character ch : charArray){
if( map.containsKey(ch) ) {
map.put(ch, map.get(ch) +1 ) ;
} else{
map.put(ch, 1);
}
}//for
// 1st non repeating character
for( int i = 0 ; i < a.length(); i ++ ){
char chh = a.charAt(i);
if( map.get(chh) == 1 ){
System.out.println("first non repeating character in the String is : ");
return chh ;
}//if
}//for
return null;
}//firstNonRepeatingCharacter
}//end
We will do this with the help of list comprehension in Python. We are not using set() operator. In Python :
string = 'GiniGinaProtijayi'
unique = []
[ unique.append(ch) for ch in string if ch not in unique ]
lengthofUniqueCharacters = len(unique)
print("length of Unique Characters => " ,lengthofUniqueCharacters)
print("as a list => ",unique)
print("as a string => " , ''.join(unique))
Just to print out the distinct characters in Java 8:
public class Test5 {
public static void main(String[] args) {
String a = "GinaGini";
String aa = a.chars().distinct()
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString();
System.out.println(aa);//Gina
}// main
}