找到最右边的字符串

时间:2017-11-08 13:20:44

标签: java string algorithm recursion methods

我正在编写一个递归算法,以便在字符列表中找到最正确的单词“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)或just(char [] A,String s,int i)?我从来都不擅长使用参数调用方法,所以感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

首先,您需要了解您想要返回的内容。

- 所以在这里你必须得到一个单词最后一次出现的索引。该怎么办?让我们抓住它。有很多方法可以做到这一点。一种方法是 -

    public class Question7 {
        public static int lastFoundIndex = -1;
        ..
    }

第二,如何启动流程?

    public static void main(String... args) {
        char[] givenArray = {'o', 't', 'z', 'y', 'e', 's', 'v', 'g', 'r', 'a', 'y', 'e', 's'};

        // this is the initializing function, where you pass 2 params
        // The array and Index from where you want to start looking.  
        where(givenArray, 0);  
        System.out.println("The rightmost occurence of 'yes' in the given array is at index "+ lastFoundIndex);
    }

接下来,让我们看一下where(..)函数的样子。

    public static void where(char[] arr, int startIndex) {
        // this is the base case. First statement. 
        // Basically for testing, if the array is empty or we reached at the end of the execution (we'll reach there soon)
        if(startIndex >= arr.length) {
            return;
        }

        // Now we check if we have the word 'yes', if so - save the lastFoundIndex. and call where function and tell it to look starting from currentIndex + 3 place.  
        if(arr[startIndex] == 'y' && startIndex + 2 < arr.length) {
            if(arr[startIndex + 1] == 'e' && arr[startIndex + 2] == 's') {
                lastFoundIndex = startIndex;
                where(arr, startIndex+3);
            }
        }

        // if we dont find the character y, then just go on with next char.  
        where(arr, startIndex+1);
    }