Complete the method numXY.
It finds the number of times the string "XY" appears in the input string recursively.
You must not use any loops or regular expressions.
Test cases:
numXY("AAXYAA") → 1
numXY("AXYBXYAA") → 2
格式:
public static int numXY(String input) {
// base case
// recursive step
}
提供一个思路,代码和注释在下面
public static int numXY(String input) {
String XY = "XY";
// base case
// 被查找的字符串为null的话,出现次数肯定为0,终止递归
if (input == null){
return 0;
}
// 如果字符串长度已经小于待查找的字符串了,说明出现次数为0,终止递归
if(input.length() < XY.length()){
return 0;
}
// count记录了被查找的字符串是否以XY开头,0不是,1是
int count = 0;
if (input.startsWith(XY)){
count++;
}
// recursive step
// 从第二个字符开始的子字符串进行递归
return numXY(input.substring(1)) + count;
}
参考下这个
public class Main {
public static void main(String[] args) {
System.out.println(numberOf("https://www.cjavapy.com", 'a'));
}
static int numberOf(String text, char characterToCount) {
return helper(text, characterToCount, 0);
}
static int helper(String text, char charToCount, int index) {
if (text.isEmpty() || index == text.length()) return 0;
int countCharOnRight = helper(text, charToCount, index+1);
return (text.charAt(index) == charToCount) ? 1 + countCharOnRight : countCharOnRight;
}
}
实现步骤和详细代码如下:
public static int numXY(String input) {
// base case
if (input.length() < 2) {
return 0;
}
// recursive step
if (input.charAt(0) == 'X' && input.charAt(1) == 'Y') {
return 1 + numXY(input.substring(2));
} else {
return numXY(input.substring(1));
}
}
功能效果
int num1 = numXY("AAXYAA"); // num1 will be 1
int num2 = numXY("AXYBXYAA"); // num2 will be 2
int num3 = numXY("XYXYXY"); // num3 will be 3