Java Scrap Book  

HOME > Java Collection >Set > Unique

Implement an algorithm to determine if a string has all unique characters What if you can not use additional data structures?

package  com.javascrapbook.com;

import  java.util.HashSet;
import  java.util.Set;

public class IsUnique {

  public static void main(String[] args) {

System.out.println(isUniqueChars("unique"));
System.out.println(isUniqueChars("world"));
}
 public static boolean isUniqueChars(String str) {
   boolean[] char_set =   new boolean[256];
  for (int i = 0; i < str.length(); i++) {
  int val = str.charAt(i);
  if(char_set[val])
   return false;
  char_set[val] = true;
 }// end of for loop
   return true;
}
}

Result

false
true