first non repeating character in the String

Find the first non repeating character in the given String str.

Example :-

1. String input = “abcd”

Output – a, because all the character in string ‘input’ is unique but ‘a’ is the first non repeating character

2. String input = “helloh’

Output – ‘e’, because ‘e’ is the the first non repeating character in input string

Solution

There are many ways to find the first non-repeating character in String. Here we are going to find the frequency of all characters in the string after that we will check the first non-repeating character in the string

Steps :-

Calculating frequency of each character in String using Java –

Our first task is to calculate frequency of each character in given string. for storing frequency of each character we are going to use array here, we can also use HashMap.

So how we are going to store the frequency of characters in an array ?

We all know that every character has an ASCII value which is in int and the range for these ASCII values is 0 To 127. So we are going to use these ASCII values as an index in a char array of length 128.

Now we have to iterate String, character by character and increase the frequency for each character in array using character’s ASCCI value as index in array

Now we have to again iterate String, character by character and check frequency for that character in the array. if frequency for character is 1 they we will return the index of that character in String. If there is no character with frequency 1 i.e., all the characters are repeated then we will return -1;

first non repeating character in a string Java Code

package thecodedata;

import java.util.Scanner;

public class NonRepeatingCharacter {

    // this method will check for first non-repeated character in string and return index of that charcter
    static int firstNonRepeatingCharacter(String s)
    {
        //array to store frequency of character
        if(s.length()==0)
            return -1; // string is empty
        char[] frequency = new char[128];
        for(int i=0;i<s.length();i++) {
            frequency[s.charAt(i)]++;// frequency increases for characters
        }
        for(int i=0;i<s.length();i++) {
            if (frequency[s.charAt(i)] == 1) {
                return i;
            }
        }
        return -1; // all the characters are repeated
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the string");
        String str = sc.nextLine();
        int index = firstNonRepeatingCharacter(str); // calling the method to find first non-repeated character in string
        if(index==-1)
            System.out.println("No character is present with frequency 1");
        else System.out.println(str.charAt(index)+" is the first non repeated character in the string");
    }

}

Output first non repeating character in the string

frequency of character in String

Leave a Comment