Skip to content

Instantly share code, notes, and snippets.

@chouclee
Created June 16, 2014 03:48
Show Gist options
  • Save chouclee/5880c7fdf95bf593c395 to your computer and use it in GitHub Desktop.
Save chouclee/5880c7fdf95bf593c395 to your computer and use it in GitHub Desktop.
[CC150][1.1] Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? (not applicable for Unicode)
import java.util.Scanner;
public class UniqueString {
public static boolean unique(String s) {
if (s == null) return false;
boolean[] flag = new boolean[256];
for (int i = 0; i < s.length(); i++) {
if (flag[s.charAt(i)])
return false;
else
flag[s.charAt(i)] = true;
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String s = in.nextLine();
if (unique(s))
System.out.println("Unique");
else
System.out.println("Not Unique") ;
}
in.close();
}
}
@jason51122
Copy link

  1. You should return the result directly when the length of string is 0 or bigger than 256.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment