Determine if the characters of a given string are all unique.

Assumptions

  • We are using ASCII charset, the value of valid characters are from 0 to 255
  • The given string is not null

Examples

  • all the characters in "abA+\8" are unique
  • "abA+\a88" contains duplicate characters

Solution: 256个ASCII码,只需8个int记录,每个bit代表该ASCII码有没有出现过。c / 32和c % 32确定bit位置

  public boolean allUnique(String word) {
    int[] map = new int[8];
    for (int i = 0; i < word.length(); i++) {
      char c = word.charAt(i);
      if (((map[c / 32] >>> (c % 32)) & 1) != 0) {
        return false;
      }
      map[c / 32] |= 1 << (c % 32);
    }
    return true;
  }

results matching ""

    No results matching ""