Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the Characters in a String Recursively & treat "eu" as a Single Character

I am new to Java, and I'm trying to figure out how to count Characters in the given string and threat a combination of two characters "eu" as a single character, and still count all other characters as one character.

And I want to do that using recursion.

Consider the following example.

Input:

"geugeu"

Desired output:

4   // g + eu + g + eu = 4

Current output:

2

I've been trying a lot and still can't seem to figure out how to implement it correctly.

My code:

public static int recursionCount(String str) {
    if (str.length() == 1) {
        return 0;   
    }
    else {
        String ch = str.substring(0, 2);
        if (ch.equals("eu") {
            return 1 + recursionCount(str.substring(1));
        }
        else {
            return recursionCount(str.substring(1));
        }
    }
}
like image 384
ScubaDivingGoldFish Avatar asked Jan 22 '26 03:01

ScubaDivingGoldFish


1 Answers

OP wants to count all characters in a string but adjacent characters "ae", "oe", "ue", and "eu" should be considered a single character and counted only once.

Below code does that:

public static int recursionCount(String str) {
    int n;
    n = str.length();
    if(n <= 1) {
        return n; // return 1 if one character left or 0 if empty string.
    }
    else {
        String ch = str.substring(0, 2);
        if(ch.equals("ae") || ch.equals("oe") || ch.equals("ue") || ch.equals("eu")) {
            // consider as one character and skip next character
            return 1 + recursionCount(str.substring(2));
        }
        else {
            // don't skip next character
            return 1 + recursionCount(str.substring(1));
        }
    }
}
like image 144
Nikhil Avatar answered Jan 25 '26 00:01

Nikhil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!