Find first non repeated character in a string in Java.

Find first non repeated character in a string in Java.


Given a string, find the first non-repeating character in it.

Lets see sample input and output:

Algorithm 


We will use the HashMap to store the character as key and number of times it is repeated as value.

Step1:
Iterate through the String and put it in HashMap, if the character key is already present in Map, increment the count.

Step2:
Iterate the String and check against the HashMap, the first occurrence of any character in a String whose repetition count is 1 is our answer.

Java program to find first non repeated character in a String.

package com.javabypatel.string;

import java.util.HashMap;
import java.util.Map;

public class FindFirstNonRepeatingCharacter {
    public static void main(String[] args) {
        String str = "madam";
        System.out.println(getFirstNonRepeatingCharacter(str));
    }

    private static char getFirstNonRepeatingCharacter(String str) {
        Map<Character, Integer> countMap = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            int count = countMap.get(str.charAt(i)) == null ? 1 : countMap.get(str.charAt(i)) + 1;
            countMap.put(str.charAt(i), count);
        }

        for (int i = 0; i < str.length(); i++) {
            if (countMap.get(str.charAt(i)) == 1) {
                return str.charAt(i);
            }
        }
        return '\0';
    }
}

Post a Comment