Java Program to find first non-repeated character in string

In this tutorial, we will see how to find the first non-repeated character in a given string in java programming language. There are many approaches to achieve this.

We can use LinkedHashMap to find the first non-repeated character in a string. Following is the algorithm:

  1. We will iterate over the length of string, extracting characters.
  2. Put this character in LinkedHashMap with its count. If already there, increment by 1.
  3. Get the count from LinkedHashMap. If the count is 1 return the character.

An important point to remember is that LinkedHashMap maintains the insertion order. Hence, we will be able to retrieve the first nonrepeating character.

Java Code:

import java.text.*;
import java.util.*;
import java.util.Map.Entry;
 
public class Main {
 public static void main(String[] args) {
  System.out.println("In String analogy is : "+ getCharacter("analogy"));
  System.out.println("In String difficult is : "+ getCharacter("difficult"));
 }
 
 public static Character getCharacter(String s) {
  Map<Character, Integer> count = new LinkedHashMap<Character, Integer>();
  int lenString=s.length();
  for (int i = 0; i < lenString - 1; i++) {
   Character c = s.charAt(i);
   if (!count.containsKey(c)) {
    count.put(c, 1);
   } else {
    count.put(c, count.get(c) + 1);
   }
  }
  for (Entry<Character, Integer> e : count.entrySet()) {
   if (e.getValue() == 1)
    return e.getKey();
 
  }
  return null;
 
 }
}

Another approach to finding the first non repeating character is to use indexOf() and lastIndexOf() inbuilt methods.

Output:

First non repeating character for analogy is : n
First non repeating character for difficult is : d

Also read,
Decimal to Binary conversion in JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *