This my solution to one of the practice problems from Cracking the Coding Interview: 150 Programming Interview Questions and Solutions [Book]
implement an algorithm to determine of a string has all unique characters. What if you cannot use additional data structures ?
public class PracticeProblems {
public void questionOne(String input) {
/*-- implement an algorithm to determine if a string has all unique characters.
* What if you cannot use additional data structures? --*/
boolean[] chars = new boolean[26];
int x = 0;
for(int i = 0; i < input.length(); i++) {
if(!chars[(int)input.toUpperCase().charAt(i) - 64]) {
chars[(int)input.toUpperCase().charAt(i) - 64] = true;
}
else {
System.out.println("not unique");
x = -1;
break;
}
}
if(x == 0)
System.out.println("unique");
}
public static void main(String[] args) {
PracticeProblems test = new PracticeProblems();
test.questionOne("dsfdddft");
}
}
I was wondering if there was a better solution to this, or if there is a better way of handling the last part, where I am initializing an x variable to be able to determine if I all the characters are not unique, not to print "it is unique". If don't have the condition for the x value it always prints "it is unique".
char
can have 2^16 = 65536 different values. What does your program return for this string "?" – abuzittin gillifirca Feb 7 at 11:44