Skip to content

Instantly share code, notes, and snippets.

@jason51122
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jason51122/cad80336bdbbe7ecd02d to your computer and use it in GitHub Desktop.
Save jason51122/cad80336bdbbe7ecd02d to your computer and use it in GitHub Desktop.
1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
public boolean uniqueChar(String str) {
if (str == null) {
throw new IllegalArgumentException();
}
int len = str.length();
if (len == 0) {
return true;
}
// There must exist at least 1 duplicated char if there are more than 256 chars.
if (len > 256) {
return false;
}
// ASCII is usually represented by 8 bits, but there are 128 different chars in total.
boolean[] flag = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int index = str.charAt(i);
if (flag[index] == true) {
return false;
}
else {
flag[index] = true;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment