【发布时间】:2018-04-21 04:56:20
【问题描述】:
我正在编写一个递归算法,以在字符列表中查找单词“yes”的最右边出现。
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
}
}
调用该方法时,我的问题在底部。我应该使用特定的参数还是不特定的参数?例如: where(givenarray, "yes", givenarray.length) 或只是 (char[] A, String s, int i)?我从来都不擅长调用带参数的方法,因此不胜感激!
【问题讨论】:
-
查看递归 (cs.cmu.edu/~15110-s13/Unit05PtA-handout.pdf) 。您在这里缺少基本情况。确保当您再次调用递归函数时,您传递的是一个较小的问题来解决。
-
你需要使用递归吗?对于这个特定的问题,将 char 数组转换为字符串并使用 lastIndexOf 可以为您提供所需的内容,而不会使事情变得过于复杂。
-
@trappski 我确实需要使用递归。
-
@ajc 我认为基本情况是 if length
-
您在基本情况之前调用了
where(..)方法。你能猜到会发生什么吗?
标签: java string algorithm recursion methods