Thursday, 25 August 2016

Java Program to find First Non Repeated Character In A String ?

If the word "stress" is input  then it should print  't'   as output .
If the word "teeter" is input  then it should print  'r'   as output .

import java.util.HashMap;
import java.util.Map;

public class FirstNonRepeatedCharacter {
    
public static Character getFirstCha(String str){
Map<Character, Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
if(map.containsKey(str.charAt(i))){
map.put(str.charAt(i), map.get(str.charAt(i))+1);
}
else{
map.put(str.charAt(i), 1);
}
}
for(int i=0;i<str.length();i++){
if(map.get(str.charAt(i)) == 1){
return str.charAt(i);
}
}
return null;
}
public static void main(String[] args) {
System.out.println("FIRST NON REPEATED CHARACTER : "+FirstNonRepeatedCharacter.getFirstCha("teeter"));
System.out.println("FIRST NON REPEATED CHARACTER : "+FirstNonRepeatedCharacter.getFirstCha("stress"));
}


Program Output :-
FIRST NON REPEATED CHARACTER : r

FIRST NON REPEATED CHARACTER : t



No comments:

Post a Comment