Skip to content

Instantly share code, notes, and snippets.

@nealhu
Last active August 29, 2015 14:02
Show Gist options
  • Save nealhu/39858575893644bc06d6 to your computer and use it in GitHub Desktop.
Save nealhu/39858575893644bc06d6 to your computer and use it in GitHub Desktop.
CC_1_1
// Cracking the code interview
// 1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
class UniqueCharacters {
public static boolean hasUniqueCharacters(String s) {
if (s == null || s.isEmpty()) return true;
int len = s.length();
if (len > 256) return false;
boolean[] hash = new boolean[256];
for(int i = 0; i < len; i++) {
char c = s.charAt(i);
if (hash[c]) {
return false;
} else {
hash[c] = true;
}
}
return true;
}
public static void main(String[] args) {
String test1 = "abc&3";
String test2 = "fd3j23";
String test3 = "";
String test4 = null;
String test5 = "A";
assert hasUniqueCharacters(test1);
assert !hasUniqueCharacters(test2);
assert hasUniqueCharacters(test3);
assert hasUniqueCharacters(test4);
assert hasUniqueCharacters(test5);
System.out.println("Test Passed");
}
}
@pchong90
Copy link

if (len > 256) return false; good catch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment