[28] Implement strStr()

10 篇文章 1 订阅
1 篇文章 1 订阅

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值