HashTable

First Non Repeated characters

Pinterest LinkedIn Tumblr

Write a program to find first non-repeating char on it using the hash table.

Algorithm Explanation

Initialize the string and pass the string to the utility function.
Create the hash map with char and integer. If the character is available in hash map key, get the value count and increment by 1. Otherwise, add the char as key and 1 as value.
Iterate all the char in the string. If the count is 1, return the values in the array.
Print the values.

Source Code

package com.dsacode.DataStructre.hashtable;
 
import java.util.HashMap;
 
public class FirstNonRepeated {
     public static Character firstNonRepeatedCharacter(String str)
        {
            HashMap < Character, Integer >  characterhashtable=new HashMap < Character ,Integer > ();
            int i,length ;
            Character c ;
            length= str.length(); 
            for (i=0;i < length;i++) {
                c=str.charAt(i);
                if(characterhashtable.containsKey(c)) {
                    characterhashtable.put(  c ,  characterhashtable.get(c) +1 );
                }else{
                    characterhashtable.put( c , 1 ) ;
                }
            }
             
            for (i =0 ; i < length ; i++ ) {
                c= str.charAt(i);
                if( characterhashtable.get(c)  == 1 )
                return c;
            }
            return null ;
        }
    public static void main(String[] args) {
            char c=firstNonRepeatedCharacter("Hello");
            System.out.println("The first non repeated character in 'Hello' is :  " + c);
 
    }
 
}

Output

The first non-repeated character in 'Hello' is :  H

Write A Comment