Java Program to check if String has all unique characters
Table of contents
Using HashSet
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Apple has all unique chars : " + hasAllUniqueChars("apple"));
System.out.println("index has all unique chars : " + hasAllUniqueChars("index"));
System.out.println("world has all unique chars : " + hasAllUniqueChars("world"));
}
private static boolean hasAllUniqueChars(String word) {
Set<Character> set = new HashSet<>();
for (int index = 0; index < word.length(); index++) {
char ch = word.charAt(index);
// If Hashset's add method return false,
// that means it is already present in HashSet
if (!set.add(ch))
return false;
}
return true;
}
}
Using ASCII value of character
Create a boolean array of 26 length
Convert char to uppercase and get its ASCII value
Subtract 64 to the ASCII value to get an index between 0 to 25.
If a character is not repeated then we should have false in the boolean array
public class Main {
public static void main(String[] args) {
System.out.println("Apple has all unique chars : " + hasAllUniqueChars("apple"));
System.out.println("index has all unique chars : " + hasAllUniqueChars("index"));
System.out.println("world has all unique chars : " + hasAllUniqueChars("world"));
}
private static boolean hasAllUniqueChars(String word) {
boolean[] charMap = new boolean[26];
word = word.toUpperCase();
for (int index = 0; index < word.length(); index++) {
// we are subtracting char's ascii value to 64,
// so we get all index from 0 to 25.
int asciiCode = (int) word.charAt(index) - 64;
// If char is not present, it should have false at that index
if (!charMap[asciiCode])
charMap[asciiCode] = true;
else
return false;
}
return true;
}
}