determine if a string has all unique characters?

前端 未结 16 1465
长发绾君心
长发绾君心 2020-12-28 08:29

Can anybody tell me how to implement a program to check a string contains all unique chars ?

16条回答
  •  醉酒成梦
    2020-12-28 09:36

    this is optimal solution for the problem. it takes only an integer variable and can tell whether it is unique or not regardless of string size.

    complexity

    best case O(1)

    worst case O(n)

    public static boolean isUniqueChars(String str) {
        int checker = 0;
        for (int i = 0; i < str.length(); ++i) {
            int val = str.charAt(i) - ‘a’;
            if ((checker & (1 << val)) > 0) 
                return false;
            checker |= (1 << val);
        }
        return true;
    }
    

提交回复
热议问题