Wednesday, October 15, 2014

Find first non repeated character from string.

There are certain methods finding non repeated character from given string.

1. Using array : Compare each character of string to other character and finding out solution.

private static Character getNon(String string) {
// TODO by character
char[] array = string.toLowerCase().toCharArray();
for (int i = 0; i < array.length; i++) {
boolean isMatch = false;
for (int j = i+1; j < array.length; j++) {
if(array[i] == array[j]){
isMatch= true;
}
}
if(!isMatch){
return array[i];
}
}
return null;
}


2. Using collection : This is second method using collection framework. In this we store char and int pair. Initially non repeated char at 1 if character repeats then index increase by 1. Just get back character from start which contains int value 1.

private static Character getNonCollection(String string) {
// TODO by collection
string = string.toLowerCase();
int iLength = string.length();
Character character;

HashMap<Character, Integer> hashMapChars = new HashMap<Character, Integer>();

for (int i = 0; i < iLength; i++) {
character = string.charAt(i);
if(hashMapChars.containsKey(character)){
hashMapChars.put(character, hashMapChars.get(character) + 1);
}else{
hashMapChars.put(character, 1);
}
}

for (int i = 0; i < iLength; i++) {
character = string.charAt(i);
if(hashMapChars.get(character) == 1){
return character;
}
}
return null;
}

No comments:

Post a Comment