5 Dec 2017

write a program in java to find first non repeating character from a given string.


To find the first non-repeating character from given string,we will put the all character based on their frequency into HashMap and we will check for that character which has only one frequency and that is our character.


Program


import java.util.*;

class FirstNonRepeated {
          public static void main(String arg[]) {
                   System.out.println("Enter String to find First non-repeating Character");
                   String s = new Scanner(System.in).nextLine();
                   fnrc(s);
          }

          public static void fnrc(String str) {
                   Character c;
                   HashMap<Character,Integerhm = new HashMap<>();
                   for (int i = 0; i < str.length(); i++) {
                             c = str.charAt(i);
                             if (hm.containsKey(c))
                                      hm.put(c, hm.get(c) + 1);
                             else
                                      hm.put(c, 1);
                   }
                   for (int i = 0; i < str.length(); i++) {
                             c = str.charAt(i);
                             if (hm.get(c) == 1)
                                      System.out.println(c);
                   }
          }
}

Output

Enter String to find First non-repeating Character
aaaabbbbcddd
c
Press any key to continue . . .