Problem
Determine if a string has all unique characters.
Solution
public class UniqueCharInString{
public static void main(String[] arguments){
String[] testCases= {"hello", "wolrd", "", " ", " a", "abcdecfa"};
for(int i = 0; i < testCases.length; ++i){
if(UniqueCharInString.HasUniqueChars(testCases[i])){
System.out.println(testCases + " has unique characters.");
}else{
System.out.println(testCases + " doesn't have unique characters.");
}
}
}
public static boolean HasUniqueChars(String string){
boolean[] table = new boolean[256];
for(int i = 0; i < string.length(); ++i){
if(table[string.charAt(i)] == false){
table[string.charAt(i)] = true;
}else{
return false;
}
}
return true;
}
}
Output
hello doesn't have unique characters.
wolrd has unique characters.
has unique characters.
has unique characters.
a has unique characters.
abcdecfa doesn't have unique characters.