Java Program to Find First Non-Repeated Character in The Given String

This post shows ways to find first non repeated character in the given String in Java. For example if the given String is “abcdcab” then the first non repeated character is d.

There are many options to write a Java program to find first non repeated character in the given String some of them are as follows.

  1. Using LinkedHashMap
  2. Using indexOf() method of the String class
  3. Write your own logic with out using any inbuilt Java method.

Find first non repeated character using LinkedHashMap

In the solution using LinkedHashMap you can iterate the String character by character and store it in the map as a (key, value) pair where character is the key and its count is value. For every character, check in the LinkedHashMap if the key already exists, if yes then increment its count otherwise store it with count as 1.
Once all the characters are stored in the map, iterate the map to look for the first key with the value 1. That would be the first non repeated character. Here LinkedHashMap is used because it maintains the insertion order that helps if you need the first non repeated character in the String.
Java program

Output

Using indexOf() method to find first non repeated character

You can also use indexOf() and lastIndexOf() method of the String class to find first non repeated character in the given String. Since indexOf() returns the index of the first occurrence of the given character and lastIndexOf() returns the index of the last occurrence of the given character in the String so the character for which index returned by both the methods is equal would be the first non repeated character.
Java Program

Output

Finding first non repeated char without using any inbuilt Java method

If you are asked to solve this problem without using any inbuilt Java method in any interview then you can use the given logic.

In an outer loop you will iterate the string character by character, in an inner for loop you will again iterate the String and compare the character from the outer loop with all the characters of the string. If a match is found that means the character is repeated, if no match found for the character then it is a non repeated character.

Output

That’s all for the topic Java Program to Find First Non-Repeated Character in The Given String. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.