Java Program to Detect Duplicate Characters Without Collections

Отвечено с помощью: GPT-4o-mini отJava Q&A Hub

Вопрос:

Write a Java program that detects the duplicate characters in a string. What if I don't let you use the collection class in Java?

Ответ:

Certainly! Below is a Java program that detects duplicate characters in a string without using any collection classes. Instead, it uses a simple array to keep track of the occurrences of each character.

import java.util.Scanner;

public class DuplicateCharacterDetector {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();
        
        // Call the method to find duplicates
        findDuplicateCharacters(input);
        
        scanner.close();
    }

    public static void findDuplicateCharacters(String str) {
        // Create an array to keep track of character counts
        int[] charCount = new int[256]; // Assuming ASCII characters

        // Count occurrences of each character
        for (int i = 0; i < str.length(); i++) {
            charCount[str.charAt(i)]++;
        }

        // Print duplicate characters
        System.out.println("Duplicate characters in the string:");
        boolean hasDuplicates = false;
        for (int i = 0; i < charCount.length; i++) {
            if (charCount[i] > 1) {
                System.out.println((char) i + " appears " + charCount[i] + " times.");
                hasDuplicates = true;
            }
        }

        if (!hasDuplicates) {
            System.out.println("No duplicate characters found.");
        }
    }
}

Explanation:

  1. Input Handling: The program prompts the user to enter a string.
  2. Character Counting: It uses an integer array charCount of size 256 (to accommodate all ASCII characters) to count the occurrences of each character in the string.
  3. Duplicate Detection: After counting, it checks the charCount array for any character that appears more than once and prints those characters along with their counts.
  4. Output: If no duplicates are found, it informs the user accordingly.

Note:

  • This program assumes that the input string contains ASCII characters. If you need to handle Unicode characters, you would need to adjust the array size and logic accordingly.