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

Write a java program to find first non-repeating character in a string. Given an input string, Write a java code to find first non-repeating 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

Find First Non-repeating Character in a String

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

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

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

Subscribe Our Tutorials

Get Latest Updates on Facebook

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-repeating 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 a 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-repeating character in a String.

Step 1: Traverse the complete 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 stack

 

Programming questions on a linked list

 

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

In this video tutorial, I have explained how we can first non-repeating character in a string using HashMap and LinkedHashMap.

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.