Unique Characters


Implement an algorithm to determine if a string has all unique characters.


Given "abc", return true.

Given "aab", return false.


What if you can not use additional data structures?


Use a set to store the unique characters, for each character in the string, if it is not in the set, add it to the set; otherwise it appeared before, return false.

If no additional data structure is allowed, sort the string and compare the adjacent characters to see if they are the same.

Code - Java

public class Solution {
     * @param str: a string
     * @return: a boolean
    public boolean isUnique(String str) {
        Set<Character> set = new HashSet<>();
        for (char c : str.toCharArray()) {
            if (set.contains(c)) {
                return false;
        return true;