Skip to content

Instantly share code, notes, and snippets.

@n2iw
Last active August 29, 2015 14:18
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 n2iw/d8b52a7f67aaa553f62f to your computer and use it in GitHub Desktop.
Save n2iw/d8b52a7f67aaa553f62f to your computer and use it in GitHub Desktop.
import java.util.HashSet;
import java.util.Set;
public class UniqueCharacters {
public static final int ALPHABET_SIZE = Character.MAX_VALUE; //assume our alphabet is 16 bits chars
public static boolean solution(String s) {
//I assume we treat null and empty string as they have unique chars
//but you should really talk this with your interviewer
if (s == null || s.length() == 0) {
return true;
}
//length is greater than alphabet size, then it must have duplicated characters
if (s.length() > ALPHABET_SIZE) {
return false;
}
Set<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (set.contains(c)) {
return false;
} else {
set.add(c);
}
}
return true;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class testUniqueCharacters {
@Test
public void test() {
assertEquals(UniqueCharacters.solution(null), true);
assertEquals(UniqueCharacters.solution(""), true);
assertEquals(UniqueCharacters.solution("a"), true);
assertEquals(UniqueCharacters.solution("abcdaef"), false);
assertEquals(UniqueCharacters.solution("abcdaef"), false);
assertEquals(UniqueCharacters.solution("abcdeff"), false);
assertEquals(UniqueCharacters.solution("abcdef"), true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment