Saturday, May 24, 2025

Unraveling Strings: Finding the Word with the Most Repeated Characters in Java

Strings are fundamental to programming, and often, we need to extract specific information from them. Today, let's tackle an interesting challenge: finding the first word in a given string that boasts the highest number of repeated characters. And to make it even more robust, we'll ensure our program gracefully handles cases where no word has any repeated characters.

The Challenge: Identifying the "Repetitive" Champion

Imagine you have a sentence like: "This is a test string with some interesting words like programming and balloon." Our goal is to identify which word, among "This", "is", "a", "test", "string", "with", "some", "interesting", "words", "like", "programming", and "balloon", has the most repeated characters. In this case, "balloon" has 'l' repeated twice, and 'o' repeated twice, which means 4 repeated characters. "programming" has 'g' repeated twice, 'r' repeated twice, and 'm' repeated twice, which means 6 repeated characters. Thus, "programming" is the word we are looking for.

Breaking Down the Problem

To solve this, we can follow a few logical steps:

 * Split the string into words: The first step is to separate the sentence into individual words.

 * Analyze each word for repeated characters: For each word, we need a way to count how many characters repeat and by how much.

 * Keep track of the maximum: As we iterate through the words, we'll need to remember the word that currently holds the record for the most repeated characters and its count.

 * Handle the "no repetition" scenario: If, after checking all words, we haven't found any with repeated characters, our program should indicate this.

Java Implementation

Let's dive into a Java solution:

import java.util.HashMap;

import java.util.Map;


public class RepeatedCharWordFinder {


    /**

     * Finds the first word in a string that has the highest number of repeated characters.

     *

     * @param text The input string.

     * @return The first word with the most repeated characters, or "-1" if no word has repeated characters.

     */

    public static String findWordWithMostRepeatedChars(String text) {

        // Split the string into words using space as a delimiter

        String[] words = text.split(" ");

        int maxRepeatedCount = -1;

        String resultWord = "-1"; // Initialize with "-1" to indicate no word found yet


        for (String word : words) {

            Map<Character, Integer> charCounts = new HashMap<>();

            int currentRepeatedCount = 0;


            // Count character frequencies within the current word

            for (char c : word.toCharArray()) {

                charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);

            }


            // Calculate repeated character count for the current word

            for (int count : charCounts.values()) {

                if (count > 1) {

                    currentRepeatedCount += count; // Add all repeated characters

                }

            }


            // Update maxRepeatedCount and resultWord if current word has more repeated characters

            if (currentRepeatedCount > maxRepeatedCount) {

                maxRepeatedCount = currentRepeatedCount;

                resultWord = word;

            } else if (currentRepeatedCount == maxRepeatedCount && resultWord.equals("-1")) {

                // If it's the first word with repeated characters and ties the max, update resultWord

                // This ensures we get the first occurrence.

                resultWord = word;

            }

        }


        // Check if a word with repeated characters was found

        if (maxRepeatedCount > 0) {

            return resultWord;

        } else {

            return "-1";

        }

    }


    public static void main(String[] args) {

        // Test cases

        System.out.println(findWordWithMostRepeatedChars("This is a test string with some interesting words like programming and balloon"));

        System.out.println(findWordWithMostRepeatedChars("hello world"));  // Output: hello

        System.out.println(findWordWithMostRepeatedChars("a quick brown fox"));  // Output: -1

        System.out.println(findWordWithMostRepeatedChars("racecar level madam")); // Output: racecar

        System.out.println(findWordWithMostRepeatedChars("programming is fun")); // Output: programming

        System.out.println(findWordWithMostRepeatedChars("apple banana orange")); // Output: apple

        System.out.println(findWordWithMostRepeatedChars("bookkeeper committee Mississippi")); // Output: bookkeeper

    }

}


How the Code Works:

 * findWordWithMostRepeatedChars(String text) method:

   * Takes the input text string.

   * String[] words = text.split(" ");: Splits the input string into an array of words using a space as the delimiter.

   * int maxRepeatedCount = -1;: Initializes a variable to keep track of the highest number of repeated characters found so far. We start with -1 to ensure any positive count will be greater.

   * String resultWord = "-1";: Initializes a variable to store the word with the highest repeated characters. It's set to "-1" initially to indicate no such word has been found yet.

 * Iterating through words:

   * for (String word : words): The code iterates through each word in the words array.

 * Counting characters within a word:

   * Map<Character, Integer> charCounts = new HashMap<>();: A HashMap is used to store the frequency of each character within the current word.

   * int currentRepeatedCount = 0;: Initializes a counter for the current word's repeated characters.

   * for (char c : word.toCharArray()): Iterates through each character in the current word by converting it to a character array.

   * charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);: This line efficiently updates the character count. getOrDefault(c, 0) returns the current count of c if it exists, otherwise 0, and then increments it.

 * Calculating repeated character count for the current word:

   * for (int count : charCounts.values()): Iterates through the character counts (values) in the charCounts map.

   * if (count > 1): If a character's count is greater than 1, it means it's a repeated character.

   * currentRepeatedCount += count;: We add the count itself to currentRepeatedCount. This way, if 'l' appears twice, we add 2; if 'e' appears three times, we add 3. This accurately reflects the total number of "repeated instances" of characters.

 * Updating the maximum:

   * if (currentRepeatedCount > maxRepeatedCount): If the current word has more repeated characters than the maxRepeatedCount found so far, we update:

     * maxRepeatedCount = currentRepeatedCount;

     * resultWord = word;

   * else if (currentRepeatedCount == maxRepeatedCount && resultWord.equals("-1")): This condition handles the scenario where multiple words might have the same highest number of repeated characters. We want the first such word. So, if resultWord is still "-1" (meaning no word with repeated characters has been found yet), and the current word matches the maxRepeatedCount, we assign it as the resultWord. This ensures we always pick the first occurrence.

 * Final Return Value:

   * if (maxRepeatedCount > 0): After checking all words, if maxRepeatedCount is greater than 0, it means at least one word had repeated characters, so we return resultWord.

   * else: Otherwise, no word with repeated characters was found, and we return "-1".

Why This Approach?

 * Clarity: The code is structured logically, making it easy to understand each step.

 * Efficiency: Using a HashMap for character frequency counting is efficient for looking up and updating counts.

 * Edge Case Handling: The program explicitly addresses the scenario where no words have repeated characters, returning "-1" as requested.

 * First Occurrence: The logic ensures that if multiple words have the same highest number of repeated characters, the first such word encountered in the string is returned.

This program provides a robust and clear solution to an interesting string manipulation problem in Java. Feel free to experiment with different input strings and observe its behavior! Happy coding!



This Content Sponsored by Buymote Shopping app


BuyMote E-Shopping Application is One of the Online Shopping App


Now Available on Play Store & App Store (Buymote E-Shopping)


Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8


Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication


No comments:

Post a Comment