Created
December 20, 2012 06:40
-
-
Save Bekt/4343340 to your computer and use it in GitHub Desktop.
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
//http://coolcodebro.blogspot.com/2012/12/determine-if-string-has-all-unique.html | |
public class IsUnique { | |
public static void main(String[] args) { | |
new IsUnique().run(); | |
} | |
void run() { | |
String str = "123456789a0"; | |
System.out.println("String: " + str); | |
System.out.println("Using hashmap: " + hasAllUnique(str)); | |
System.out.println("Using array: " + hasAllUnique1(str)); | |
System.out.println(); | |
str = "AbCcdefbz"; | |
System.out.println("String: " + str); | |
System.out.println("Using hashmap: " + hasAllUnique(str)); | |
System.out.println("Using array: " + hasAllUnique1(str)); | |
} | |
//Using map | |
boolean hasAllUnique(String str) { | |
Map<Character, Integer> map = new HashMap<Character, Integer>(); | |
for(int i=0; i<str.length(); i++) { | |
char currChar = str.charAt(i); | |
if(map.get(currChar) == null) | |
map.put(currChar, 1); | |
else | |
return false; | |
} | |
return true; | |
} | |
//Using arrays. Assumption: all characters are ASCII | |
boolean hasAllUnique1(String str) { | |
boolean[] taken = new boolean[256]; | |
for(int i=0; i<str.length(); i++) { | |
int index = (int) str.charAt(i); | |
if(taken[index]) | |
return false; | |
taken[index] = true; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment