Day 1 (Problems completed: 1)
Problem:
Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
boolean allUnique(String s) {
boolean rval = true;
// Java uses two-byte chars, so lets initialize an array of size 2^16
boolean[] trackChars = new boolean[Math.pow(2, 16)];
for (int i = 0; i < s.length; i++) {
int charAsNum = Character.getNumericValue(s.charAt(i));
if (!trackChars[charAsNum]) {
trackChars[charAsNum] = true;
}
else {
rval = false;
break;
}
}
return rval;
}
No comments:
Post a Comment