Monday, February 29, 2016

Unique Characters

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

Example
Given "abc", return true. Given "aab", return false.

Challenge
What if you can not use additional data structures?

思路: 用一个哈希表存每一个字符,如果遇到重复,返回false。

public class Solution {
    /**
     * @param str: a string
     * @return: a boolean
     */
    public boolean isUnique(String str) {
        // write your code here
        HashSet<Character> hash = new HashSet<Character>();
        
        for (int i = 0; i < str.length(); i++) {
            if (!hash.contains(str.charAt(i))) {
                hash.add(str.charAt(i));
            }
            else {
                return false;
            }
        }
        return true;
    }
}
 

不用额外数据结构。用两个循环暴力一下。

public class Solution {
    /**
     * @param str: a string
     * @return: a boolean
     */
    public boolean isUnique(String str) {
        // write your code here
        for (int i = 0; i < str.length() -1 ; i++) {
            for (int j = i + 1; j < str.length(); j++) {
                if (str.charAt(j) == str.charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }
}