문자 목록에서 단어 "예"의 가장 오른쪽 항목을 찾기 위해 재귀 알고리즘을 작성했습니다.문자열의 가장 오른쪽 발생 찾기
public class Question7 {
public static int where(char[] A, String s, int i) {
// A recursive function where()
// Return the location of rightmost occurence of a given string s in a given array A
// Complete the where function
// You may want to add more parameters to the where function
s = "yes";
where(A, s, A.length);
if (A.length < 3) {
return -1;
} else if (A.length == 3) {
if (A[i - 2] == s.charAt(0) && A[i - 1] == s.charAt(1) && A[i] == s.charAt(2)) {
return i - 2;
} else {
return -1;
}
} else {
if (A[i - 2] == s.charAt(0) && A[i - 1] == s.charAt(1) && A[i] == s.charAt(2)) {
return i - 2;
} else {
return where(A, s, i - 1);
}
}
}
public static void main(String[] args) {
char[] givenarray = {'o', 't', 'z', 'y', 'e', 's', 'v', 'g', 'r', 'a', 'y', 'e', 's'};
// Test your method
System.out.println("The rightmost occurence of 'yes' in the given array is at index " + where());
// Your method should return 10
}
}
메서드를 호출 할 때 내 문제가 있습니다. 특정 매개 변수 또는 특정 매개 변수를 사용해야합니까? 예를 들면 다음과 같습니다. (givenarray, "yes", givenarray.length) 또는 그냥 (char [] A, String s, int i)? 필자는 매개 변수가있는 메서드를 호출하는 것을 매우 잘 해본 적이 없으므로 어떤 도움도 받으실 수 있습니다!
재귀 (https://www.cs.cmu.edu/~15110-s13/Unit05PtA-handout.pdf)를 살펴보십시오. 여기에 기본 케이스가 없습니다. 재귀 함수를 다시 호출 할 때 문제를 해결하기 위해 전달해야합니다. – ajc
재귀를 사용해야합니까? char 배열을 String으로 변환하고 lastIndexOf를 사용하여이 특정 문제를 해결하면 복잡하게하지 않고 필요한 것을 얻을 수 있습니다. – trappski
@ trappski 재귀를 사용해야합니다. – Katie