-
-
Save n2iw/d8b52a7f67aaa553f62f 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
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; | |
} | |
} |
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
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