Number of characters 'x' per line - Recursion

I deal with quite complex recursion issues in Java.

"Given the string, recursively (no loops) calculate the number of lowercase characters" x "in the string"

countX("xxhixx") → 4

countX("xhixhix") → 3

countX("hi") → 0

-

 public int countX(String str) {
      if (str == null || str.length() == 0)
        return 0;
      else if (str.length() == 1)
        return str.charAt(0) == 'x' ? 1 :0;
      else {
        return (str.charAt(str.length()-1) == 'x' ? 1 : 0 ) + countX(str.substring(0,str.length()-1));
      }
    }

It works great. But I would like to know if there is a better way to write this. I find this code complex for a simple problem.

+4
source share
5 answers

, , , , . . , , , . ( , String.substring, , , ).

, , , , , :

public int countX(String str) {
    if(str == null || str.isEmpty())
        return 0;
    return (str.charAt(0) == 'x' ? 1 : 0) + countX(str.substring(1));

null , 1 .

, substring . str.length().

+5

1 - else:

public int countX(String str) {
    if (str == null || str.length() == 0)
        return 0;
    }
    return (str.charAt(str.length()-1) == 'x' ? 1 : 0 ) + 
           countX(str.substring(0,str.length()-1));
}
+1

?

public static int countX(String str) {
        if (str.length() == 0) {
            return 0;
        }
        int count = 0;
        if (str.charAt(0) == 'x') {
            count++;
        }
        return count + countX(str.substring(1));
    }
+1

:

public int countX(String str) {
  if (str == null)
    return 0;
  else {
        int occurrence = str.lastIndexOf("x");
        int count = occurrence > -1 ? 1 + countX(str.substring(0, occurrence)) : 0;

        return count;
  }
}
+1

else if (str.length() == 1) , return (str.charAt(...

, , . , , ( , ...), , .

0

Source: https://habr.com/ru/post/1671391/


All Articles