Java Program to Find the First Non-repeated Character in a String

Write a java program to find the first non-repeated character in a string.Given an input string, we have to write a java code to find the first non-repeated character in a string.

For example –

i) Input string – java
Output – j (j is the first non-repeating character in a string)

ii) Input string – web rewrite
Output – b (b is the first non-repeating character in a string)

Java Program to Find the First Non-repeated Character in a String

Java Program to Find the First Non-repeated Character in a String

Java Program to Find the First Non-repeated character in a String using HashMap

In this solution, we are going to use Java HashMap to find the first non-repeated character in a String.

Subscribe Our Tutorials

Get Latest Updates on Facebook

Step 1: Traverse the String and store character and their count in a HashMap
Step 2: Traverse the String again and check the count for each character in a Map. We are traversing the string again from first to last character as HashMap doesn’t maintain the insertion order. Once we found the character with count 1 we break the loop.

Java Program to Find the First Non-repeated character in a String using LinkedHashMap

In this solution, we are going to use LinkedHashMap to store character and their count. Java LinkedHashMap maintains the insertion order. So once we scanned the String, we just need to iterate through LinkedHashMap and choose the first entry with a value 1.

Java LinkedHashMap to find the first non-repeated character of a String.

Step 1: Scan the whole string and create a map for character and their count.
Step 2: Loop through LinkedHashMap to find an entry with a value 1.

Programming questions on linked list

Conclusion

I have explained java program to find the first non-repeated character in a string using HashMap and LinkedHashMap. If you know some other efficient way to solve this problem you can let us know through your comments.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.