How to find duplicate character in a string without built in methods in java

We can find duplicate characters in a string with built in methods such as HashMap, HashSet and list too but it can have time complexity O(n*n) so that programming with out using can execute it with O(n) time complexity hence using programming will be efficient. Following is the program to find duplicates with out using built in methods.

Explanation: In this program, I created a class named FindDuplicatesWithoutBuiltInMethod and added the @Test annotation to the findDuplicates() method, which is used to find duplicate characters in a string. Within the findDuplicates() method, I initialized a string variable str with the input text to check for duplicates. I also initialized an integer array charCount to store the count of each character’s occurrences, and a character variable ch with the value '\0' to hold individual characters during processing.

Next, I calculated the length of the string and assigned it to the variable len. Using a for loop, I iterated through each character of the string using str.charAt(i), obtained its ASCII value, and incremented the corresponding count in the charCount array. In the second for loop, I iterated through the charCount array to identify and print the duplicate characters along with their counts.

import org.testng.annotations.Test;

public class FindDuplicatesWithoutBuiltInMethod {

@Test
public void findDuplicates() {

    String str = "ababcd";

    if (str == null || str.isEmpty()) {
        System.out.println("String is empty or null.");
        return;
    }

    int[] charCount = new int[256];
    int len = str.length();
    char ch = '\0';

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

    boolean duplicateMatch = false;

    // Check for duplicates
    for (int i = 0; i < 256; i++) {
        if (charCount[i] > 1) {
            ch = (char) i;
            System.out.println("Duplicate character found: '" + ch + "' appears " + charCount[i] + " times.");
            duplicateMatch = true;
        }
    }

    if (!duplicateMatch) {
        System.out.println("No duplicates are found.");
    }
}

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x