Tuesday, 2 June 2020

Print the Duplicate Letters in a String in Java

package com.sk.demos;
import java.util.*;
public class FindDuplicates {
    public static void main(String[] args) {
        String input = "SURESH";
        
        // Call the function to print duplicate characters
        printDuplicates(input);
    }

    // Function to print duplicate characters using List
    public static void printDuplicates(String input) {
    // List to keep track of characters we've seen
        List<Character> seen = new ArrayList<>();  
     // Set to store duplicates
        Set<Character> duplicates = new HashSet<>();  
        
        // Iterate through the string and identify duplicates
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            
            // Check if we've seen the character already
            if (seen.contains(ch)) {
            // Add to duplicates if it's already in seen
                duplicates.add(ch);  
            } else {
            // Otherwise, add it to the seen list
                seen.add(ch); 
            }
        }
        
        // Print duplicates
        if (duplicates.isEmpty()) {
            System.out.println("No duplicate characters found.");
        } else {
            System.out.println("Duplicate characters:");
            for (char ch : duplicates) {
                System.out.println(ch);
            }
        }
    }
}
output:
============
S

No comments:

Post a Comment