Java查找指定字符串第一次或最后一次出现的位置

思路
1. 将输入的字符串转换为char 数组
2. 从第一个字符位置开始比较,并记录匹配的次数,如果匹配的次数等于查找字符串的长度就停止检索
3. 如果找不到匹配字符串的位置返回-1

/**
     * Returns the index within the given input string of the first occurrence
     * of the specified substring.
     * 
     * @param input
     * @param query
     */
    public static void getFirstMatchingIndex(String input, String query) {
        char[] inputChars = input.toCharArray();
        char[] queryChars = query.toCharArray();
        int inputLength = input.length();
        int queryLength = query.length();

        int inputIndex = 0;
        int queryIndex = 0;
        while (inputIndex < inputLength && queryIndex < queryLength) {
            if (inputChars[inputIndex] == queryChars[queryIndex]) {
                queryIndex++;
                inputIndex++;
            } else {
                inputIndex = inputIndex - queryIndex + 1;
                queryIndex = 0;
            }
        }

        int index = queryIndex == queryLength ? (queryLength > 1 ? inputIndex - queryLength : inputIndex - 1) : -1;
        System.out.println("first matching index:" + index);
    }

/**
     * Returns the index within this string of the rightmost occurrence of the 
     * specified substring.
     * 
     * @param input
     * @param query
     */
    public static void getLastMatchingIndex(String input, String query) {
        char[] inputChars = input.toCharArray();
        char[] queryChars = query.toCharArray();
        int inputLength = input.length();
        int queryLength = query.length();
        int inputIndex = inputLength - 1;
        int queryIndex = queryLength - 1;
        int matchingLenght = 0;
        while (inputIndex >= 0 && queryIndex >= 0) {
            if (inputChars[inputIndex] == queryChars[queryIndex]) {
                inputIndex--;
                queryIndex--;
                matchingLenght++;
            } else {
                inputIndex = matchingLenght <= 0 ? (inputIndex - 1) : inputIndex;
                queryIndex = queryLength - 1;
                matchingLenght = 0;
            }
            System.out.println("i:" + inputIndex + ",q:" + queryIndex);
        }
        System.out.println("last matching index:" + (matchingLenght == queryLength ? (inputIndex + 1) : -1));
    }

测试

getFirstMatchingIndex("ssssdeffsdfsdf", "sdf");
----->
first matching index:8



getFirstMatchingIndex("ssssdeffsdfsdf", "sdf");

--->

 
   

你可能感兴趣的:(Java,算法)