This blog is all about to learn Core Java Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Previously we have discussed the Program for
Java Program to find Minimum & Maximum Element From ArrayList Or Collection ?
The most Important Question usually ask in Interviews that Write a Program to find First Non Repeated Character In A String ? In this Program we learn how to find First Non Repeated Character from String Using HashMap<K,V>. If u do not know about HashMap Please Click Here to Learn What is HashMap<K,V>.
For Example :-
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
Java I/O Tutorial
No comments:
Post a Comment