Write a program to find the first non-repeating character of a string.
The easiest solution to this would be to take each character and compare it with rest of the characters. If there is no match, then that is the first non-repeating character.But you realize the problem with this solution, right. It is very in-efficient. It takes n*n iteration.
Another solution is - create a hashmap of characters and their frequencies
- browse through all characters in the string
- if the character is present in map, increment its count
- if not present add it to map with count as 1
- if the count is >1, skip to next character
- if the count is 1, return that character - we have found our first non-repeating character.
import java.util.HashMap; import java.util.Scanner; public class NonRepeating { char firstNonRepeating(String str){ char [] arr = str.toCharArray(); HashMap<Character,Integer> map = new HashMap<>(); for (char ch :arr){/*create a map of characters and frequencies*/ if(map.containsKey(ch)){ int count = map.get(ch); map.replace(ch,count,count+1); }else{ map.put(ch,1); } } for(char ch:arr){ int frequency = map.get(ch); if(frequency==1) return ch; } return (char) -1; } public static void main(String args[]){ Scanner scanner = new Scanner(System.in); System.out.println("Enter the string:"); String str = scanner.nextLine(); NonRepeating obj = new NonRepeating(); char nonRepChr = obj.firstNonRepeating(str); if((int)nonRepChr!=-1) System.out.println("The first non-repeating character is "+nonRepChr); else System.out.println("There are no such characters"); } }
Comments
Post a Comment