It is a most basic question asked in interviews to check if string contains all unique characters or not.
Below sample program is a basic solution to this problem.
/**
*
*/
/**
* Program to determine if a string has all unique characters.
*
* @author Dixit
*
*/
public class StringUniqueCharacters {
/**
* @param args
*/
public static void main(String[] args) {
String firstString = "America";
String secondString = "India";
String thridString = "Italy";
System.out
.println("Result:" + isUniqueChars(firstString.toLowerCase()));
System.out.println("Result:"
+ isUniqueChars(secondString.toLowerCase()));
System.out
.println("Result:" + isUniqueChars(thridString.toLowerCase()));
}
public static boolean isUniqueChars(String str) {
//Initialise a boolean array
boolean[] char_set = new boolean[256];
for (int i = 0; i < str.length(); i++) {
//get ASCII value of characters
int val = str.charAt(i);
//Check in the boolean array if it is unique then set the value to true at corresponding index position
//if value is already set at the required index position then return false
if (char_set[val])
return false;
char_set[val] = true;
}
return true;
}
}
Enjoy Programming.
Why you took 256 as the array size ?
ReplyDeleteDepending upon the Input.Currently We dont have large input,array size of 256 will suffice our solution.
Delete