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'; } }
You may also like to see
Sort Linked list using Merge sort
Bubble Sort
Heap Sort
Selection Sort
Insertion Sort
How ConcurrentHashMap works and ConcurrentHashMap interview questions
How Much Water Can A Bar Graph with different heights can Hold
Interview Questions-Answer Bank
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
Post a Comment