Java Program to find the last non repeating character of a string

Java program to find the last non repeating character of a String :

This program is to find the last non repeating character of a string. To solve this problem , we are going to use extra space, i.e. extra variable to store the count of each characters. Following algorithm we are going to use :

Algorithm :

1. Scan the string from start to end. Store count of each character in a map.
2. Now, scan the string again from end to start.
3. For each character, check its count. If the count is ‘1’, that means it is the last non repeating character, return it.

For storing count of characters, we are using ‘HashMap’ . Using ‘get’ and ‘put’ method of the HashMap, we can update and read its value. Let’s take a look into the program :

Java Program :

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    /**
     * Utility function to print
     */
    private static void println(String str) {
        System.out.println(str);
    }

    private static void print(String str) {
        System.out.print(str);
    }


    private static Character findLastNonRepeatingCharacter(String string) {
        HashMap<Character, Integer> characterMap = new HashMap<>();

        //iterate the string and store count of each character in the map
        for (int i = 0; i < string.length(); i++) { Character currentCharacter = string.charAt(i); if (characterMap.containsKey(currentCharacter)) { //character is already added to the map. Increment the count. characterMap.put(currentCharacter, characterMap.get(currentCharacter) + 1); } else { //character is not added to the map. add it with value as 1 characterMap.put(currentCharacter, 1); } } for (int i = string.length() - 1; i >= 0; i--) {
            if (characterMap.get(string.charAt(i)) == 1) {
                return string.charAt(i);
            }
        }

        return null;
    }

    public static void main(String[] args) throws java.lang.Exception {

        String userInputString;
        Scanner scanner = new Scanner(System.in);

        println("Enter a string : ");
        userInputString = scanner.nextLine();

        Character c = findLastNonRepeatingCharacter(userInputString);

        if (c == null) {
            println("No character found.");
        } else {
            println("Last non repeating character is " + c);
        }
    }

}

Sample Output :

Enter a string : 
hello
Last non repeating character is o

Enter a string : 
aabbccddeeffgghhii
No character found.

Enter a string : 
Hello World
Last non repeating character is d
Sitewide-USD 336x280

Leave a Reply