1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures.

思路: 假设给定字符串用的是ASCII编码,那么总共就只有256个字符,新建一个256个元素的boolean数组, 遍历字符串,将出现的字符在boolean数组所在位置置 1。如果碰到已经置一,表明出现重复字符,返回false。

public class IsUniqueChars_1 {
  
    public boolean solu(String s) {
        boolean table[] = new boolean[256];
        for (int i = 0; i < s.length(); i++) {
            int ascii = (int) s.charAt(i);
            if (table[ascii])
                return false;
            else
                table[ascii] = true;
        }
        return true;
    }
}

优化:如果字符串长度超过256,肯定出现过重复字符了。这是只要直接返回 false 就行

public class IsUniqueChars_1 {
    
    public boolean solu(String s) {
        if (s.length() > 256)
            return false;
        boolean table[] = new boolean[256];
        for (int i = 0; i < s.length(); i++) {
            int ascii = (int) s.charAt(i);
            if (table[ascii])
                return false;
            else
                table[ascii] = true;
        }
        return true;
    }
}

2015-09-16

原文地址:https://www.cnblogs.com/whuyt/p/4813475.html