Saturday, August 3, 2013

Coding Exercises Day 1 (Problem #1)

I've decided to start honing my skills by working on a coding problem every day. The code might not be correct and it might not even compile, but the important thing is to code something each day.

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