[28] Implement strStr()

来源:互联网 发布:java调用百度地图定位 编辑:程序博客网 时间:2024/06/02 04:20

1. 题目描述

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

给定两个字符串,判断一个字符串是不是另一个字符串的子串,如果是返回第一个字串位置,如果不是返回-1。

2. 解题思路

String自带一个函数叫做indexOf,并且有两种重载,一种为indexOf(String str),另一种为indexOf(String str, int fromIndex),第一种是从0开始匹配,第二种是从给定的位置开始匹配,第一种内部通过调用indexOf(str, 0)来实现。
那么到底这个函数内部是怎么实现的呢?
源码中的主要思想是,使用一个i先找到第一个匹配的位置,然后检查之后的串与子串匹配不匹配,匹配直接返回i,遇到不匹配的从i+1开始继续匹配。
当然源码中还包括一些边界上的考虑,起始不太明白他里面给的Offset是要干嘛,默认不都是0嘛,后来理解了一下,可能是因为我这个需求可以是给定的source就是子串,给定的target也是个子串,这样就可以用Offset进行截取啦,但是为啥只有左边的没有右边的呢?而且当前源码并没有对于offset的验证,那么如果传入负值,直接就崩啦。但是这个方法是一个没有声明可见性的方法,那么他是一个仅java.lang包内可见的方法,可能不太需要验证吧。

3. Code

public class Solution {    public int strStr(String haystack, String needle)    {        // 直接使用indexOf        return haystack.indexOf(needle);    }}
// indexOf(String str)源码,返回str第一次出现的位置,如果从未出现返回-1    /**     * Returns the index within this string of the first occurrence of the     * specified substring.     *     * <p>The returned index is the smallest value <i>k</i> for which:     * <blockquote><pre>     * this.startsWith(str, <i>k</i>)     * </pre></blockquote>     * If no such value of <i>k</i> exists, then {@code -1} is returned.     *     * @param   str   the substring to search for.     * @return  the index of the first occurrence of the specified substring,     *          or {@code -1} if there is no such occurrence.     */    public int indexOf(String str) {        return indexOf(str, 0);    }
// indexOf(String str, int fromIndex)源码,返回从fromIndex起第一次出现位置,没有出现过返回-1    /**     * Returns the index within this string of the first occurrence of the     * specified substring, starting at the specified index.     *     * <p>The returned index is the smallest value <i>k</i> for which:     * <blockquote><pre>     * <i>k</i> &gt;= fromIndex && this.startsWith(str, <i>k</i>)     * </pre></blockquote>     * If no such value of <i>k</i> exists, then {@code -1} is returned.     *     * @param   str         the substring to search for.     * @param   fromIndex   the index from which to start the search.     * @return  the index of the first occurrence of the specified substring,     *          starting at the specified index,     *          or {@code -1} if there is no such occurrence.     */    public int indexOf(String str, int fromIndex) {        return indexOf(value, 0, value.length,                str.value, 0, str.value.length, fromIndex);    }
    /**     * Code shared by String and StringBuffer to do searches. The     * source is the character array being searched, and the target     * is the string being searched for.     *     * @param   source       the characters being searched.     * @param   sourceOffset offset of the source string.     * @param   sourceCount  count of the source string.     * @param   target       the characters being searched for.     * @param   targetOffset offset of the target string.     * @param   targetCount  count of the target string.     * @param   fromIndex    the index to begin searching from.     */    static int indexOf(char[] source, int sourceOffset, int sourceCount,            char[] target, int targetOffset, int targetCount,            int fromIndex) {        // 开始查找的位置越过源数组        if (fromIndex >= sourceCount) {            // 如果目标char数组为空,返回最后一个值,如果不为空返回-1            return (targetCount == 0 ? sourceCount : -1);        }        // 如果开始查找的位置小于0,将开始查找的位置修正为0        if (fromIndex < 0) {            fromIndex = 0;        }        // 如果目标char数组为空,返回第0个位置就匹配了        if (targetCount == 0) {            return fromIndex;        }        // 左边界是第一个元素        char first = target[targetOffset];        // 右边界为源串的左边界+(源串的长度-目标串的长度)        int max = sourceOffset + (sourceCount - targetCount);        // 起始i=源串的左边界+开始匹配位置        for (int i = sourceOffset + fromIndex; i <= max; i++) {            /* Look for first character. */            // 找到第一个字母匹配的地方            if (source[i] != first) {                while (++i <= max && source[i] != first);            }            /* Found first character, now look at the rest of v2 */            if (i <= max) {                int j = i + 1;                int end = j + targetCount - 1;                // 检查后续的串是否匹配                for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++);                if (j == end) {                    /* Found whole string. */                    return i - sourceOffset;                }            }        }        return -1;    }
0 0
原创粉丝点击