-
-
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?
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
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