Find First Non-repeated Character in a String – Java Code

Write a java program to find first non-repeated character in a string. Given an input string, find it’s 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 First Non-repeated Character in a String

Find First Non-repeated character in a String using HashMap – Java Code

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

Subscribe Our Tutorials

Get Latest Updates on Facebook

Step 1: Traverse the String and store each character and their count in a HashMap.
Step 2: In the next step, let’s traverse the string again and check the count for each character in a Map. Once we found the character with count 1 we break the loop.

We are traversing the string again from first to the last character as HashMap doesn’t maintain the insertion order. 

 

Java Program to Find 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 traversed the string and created the map of character and it’s count, 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 a linked list

 

Find First Non-Repeated Character in a String – Video Tutorial

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.