'Counting unique characters in a String given by the user
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 advanced Java classes like Map, Set, etc. I can only use arrays, Strings, for loops, while loops, if statements. I am trying to use a nested loop but am getting confused about how to write the algorithm for the second for loop.
public static int countUniqueCharacters(String input){
String orgInput = input.toLowerCase();
int count = 0;
int stringLength = input.length();
for( int i = 0; i<stringLength; i++){
for(int j = 2; j > j-i-1; j--){
char temp = orgInput.charAt(i);
if (temp == orgInput.charAt(j)){
count++;
Solution 1:[1]
It is extremely easy :)
public static int countUniqueCharacters(String input) {
boolean[] isItThere = new boolean[Character.MAX_VALUE];
for (int i = 0; i < input.length(); i++) {
isItThere[input.charAt(i)] = true;
}
int count = 0;
for (int i = 0; i < isItThere.length; i++) {
if (isItThere[i] == true){
count++;
}
}
return count;
}
Example for input "aab"
First for-cycle goes 3 times, each time for one char.
Value of "a" is 97, so it turns isItThere[97] to true, then second "a" is involved, which is doing the same, isItThere[97] is set to true again (hence changing nothing).
After that "b" is involved, value of char "b" is 98, therefore isItThere[98] is set to true.
And then you have second for-cycle, where you cycle through the all isItThere array. If you find any true statement, you increment count. In our case, you find isItThere[97] and isItThere[98] as true statement, it means you increment twice and returning 2.
Solution 2:[2]
Using Java 8 you could do the following:
public static long countUniqueCharacters(String input) {
return input.chars()
.distinct()
.count();
}
This creates an IntStream
of char
s, then takes only distincts values and then counts the number of occurences.
Solution 3:[3]
Here another solution:
public static int countUniqueCharacters(String input) {
String buffer = "";
for (int i = 0; i < input.length(); i++) {
if (!buffer.contains(String.valueOf(input.charAt(i)))) {
buffer += input.charAt(i);
}
}
return buffer.length();
}
The first occurance of each character is stored in buffer
. Therefore you have of all characters one in buffer
, therefore buffer.length()
delivers the count you need.
Solution 4:[4]
If your stuck on Java 7, you can use an ArrayList and just add unique values to it, then return the size of the ArrayList, which should always work even if the count is zero.
import java.util.ArrayList;
public int getUniqeCount( String arg )
{
ArrayList<Character> unique = new ArrayList<Character>();
for( int i = 0; i < arg.length(); i++)
if( !unique.contains( arg.charAt( i ) ) )
unique.add( arg.charAt( i ) );
return unique.size();
}
Solution 5:[5]
public static int countUniqueChars (String buf) {
HashSet<Character> hash = new HashSet<>();
buf = buf.toUpperCase();
for (int i = 0; i < buf.length(); i++)
hash.add(buf.charAt(i));
return hash.size();
}
Solution 6:[6]
In case you are allowed to use Java Sets, The following code is readable, compact and doing the job smoothly
public static int countUniqueChar(String word){
Set<Character> wordSet = new HashSet<>();
for(Character c : word.toCharArray())
wordSet.add(c);
return wordSet.size();
}
Solution 7:[7]
String myString = "";
for(int i=0; i< word.length(); i++) {
if(myString.indexOf(word.charAt(i)) == -1) {
System.out.println(word.charAt(i));
myString = myString + word.charAt(i);
}
}
return myString.length();
Solution 8:[8]
public static long calculateDistinctSubStringSum(String text) {
Map<String, Integer> map = new HashMap<String, Integer>();
char[] charAarry = text.toCharArray();
for (int i = 0; i < charAarry.length; i++) {
map.put(charAarry[i] + "", 1);
}
return map.size();
}
This is what I did to calculate but I am still looking for any fast way. If anyone knows please answer.
Solution 9:[9]
You can use HashSet collections for counting the unique elements in a string. It allow only unique element.
Code Snippet
public static int uniqueCount(String str)
{
HashSet<Character> al = new HashSet<Character>();
char[] arr= str.toCharArray();
for (int i=0; i<arr.length; i++)
{
al.add(arr[i]);
}
return al.size() ;
}
Refer this link to get full code: ideone
Solution 10:[10]
Try to see if the following code helps you:
String myString = "";
for(int i=0; i< word.length(); i++) {
if(myString.indexOf(word.charAt(i)) == -1) {
System.out.println(word.charAt(i));
myString = myString + word.charAt(i);
}
}
return myString.length();
Solution 11:[11]
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter String:");
int length = scanner.nextInt();
char[] ch1 = new char[length];
String[] input = new String[length];
for (int i = 0; i < length; i++) {
String userInput = scanner.next();
input[i] = userInput;
ch1= userInput.toCharArray();
Arrays.sort(ch1);
System.out.println(ch1);
}
Solution 12:[12]
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<Character> set = new HashSet<Character>();
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<Character, Integer> 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
}
Solution 13:[13]
Since you can't use advanced JAVA classes like this:
int solution(String s) {
return (int) s.chars().distinct().count();
}
You can count each character in its own array index by ASCII:
int solution(String s) {
//1. Create a ASCII char array
//2. count chars into array.
//3. loop array and return count of each greater than 0
int[] a = new int[128];
for(int i=0; i<s.length(); i++)
a[s.charAt(i)] += 1;
int count = 0;
for(int i=0; i<a.length; i++)
if(a[i] > 0)
count += 1;
return count;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow