We can determine a String has all unique characters or not by several ways.
Suppose you are given a String like "abcdef10&g" and our program should return TRUE as it contains all unique characters, but for a String like "abccdefg", the output would be FALSE.
I am going to use a boolean array to solve this approach. Initially each element of the array would be FALSE. We will find out the ASCII value of each character and check the current value for that index in boolean array, if the value is FALSE that means the character is unique and make the value TRUE.
If the value is TRUE that means character is already present and the String contains non-unique characters.
Sample Code:
/**
*
* @author Sourin M
*
*/
public class UniqueString {
public static void main(String[] args) {
String uniqueTest="abcdef10gg";
if(isUniqueChanracter(uniqueTest))
System.out.println("Yes, Unique String.");
else
System.out.println("No, its not unique ");
}
private static boolean isUniqueChanracter(String uniqueTest) {
boolean unique_set[]=new boolean[256];
for(int i=0;i<uniqueTest.length();i++)
{
int val=uniqueTest.charAt(i);
if(unique_set[val])
return false;
else
unique_set[val]=true;
}
return true;
}
}
Suppose you are given a String like "abcdef10&g" and our program should return TRUE as it contains all unique characters, but for a String like "abccdefg", the output would be FALSE.
I am going to use a boolean array to solve this approach. Initially each element of the array would be FALSE. We will find out the ASCII value of each character and check the current value for that index in boolean array, if the value is FALSE that means the character is unique and make the value TRUE.
If the value is TRUE that means character is already present and the String contains non-unique characters.
Sample Code:
/**
*
* @author Sourin M
*
*/
public class UniqueString {
public static void main(String[] args) {
String uniqueTest="abcdef10gg";
if(isUniqueChanracter(uniqueTest))
System.out.println("Yes, Unique String.");
else
System.out.println("No, its not unique ");
}
private static boolean isUniqueChanracter(String uniqueTest) {
boolean unique_set[]=new boolean[256];
for(int i=0;i<uniqueTest.length();i++)
{
int val=uniqueTest.charAt(i);
if(unique_set[val])
return false;
else
unique_set[val]=true;
}
return true;
}
}
No comments:
Post a Comment