Skip to content

Instantly share code, notes, and snippets.

@startupjing
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupjing/dfd6a05aa122d53afb05 to your computer and use it in GitHub Desktop.
Save startupjing/dfd6a05aa122d53afb05 to your computer and use it in GitHub Desktop.
my solutions--cc150 1.1
import java.util.*;
public class UniqueChar {
/**
* ask for user input and check if it has unique character
* @param args
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string (q to quit): ");
while(input.hasNextLine()){
String userStr = input.nextLine();
if(userStr.equals("q")){
System.out.println("quit...");
System.exit(0);
}
System.out.println(userStr + "has unique char? " + hasUniqueChar(userStr));
System.out.println();
System.out.println("Please enter another string (q to quit): ");
}
}
/**
* check if the given string has unique character
* @param s
* @return true if string has unique character and false otherwise
*/
public static boolean hasUniqueChar(String s){
//some special checks
if(s == null){
throw new IllegalArgumentException();
}else if(s.length() == 0){
return true;
}else if(s.length() >256){
return false;
}
//boolean array of length 256
boolean[] arr = new boolean[256];
//traverse the string and find ASCII value for each char
for(int i=0; i<s.length(); i++){
int val = s.charAt(i);
//check if duplicate exists
if(arr[val]){
return false;
}
arr[val] = true;
}
return true;
}
}
@jason51122
Copy link

  1. Please check the edge case when input string is null.
  2. You can return the result directly when the lengths of input string is 0 or bigger than 256.

@startupjing
Copy link
Author

Thanks for your comments~~

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