Last active
August 29, 2015 14:02
-
-
Save nealhu/39858575893644bc06d6 to your computer and use it in GitHub Desktop.
CC_1_1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if (len > 256) return false;
good catch