每天一个小程序(五)--- Implement strStr()

21 篇文章 0 订阅
14 篇文章 0 订阅
本文介绍了如何在不使用Java String内置方法indexOf()的情况下实现strStr()。作者分享了他们在五一假期后的思考,并提供了一种解决方案,该方案的时间复杂度为O(m*n),空间复杂度为O(1)。详细代码可在github查阅。
摘要由CSDN通过智能技术生成

Implement IndexOf

皆さん、ただいま、祝日(しゅくじつ)は楽しいですか?

学生会的一己之见

前言:

五一大家有没有出(堵)去(成)玩(狗)呀,感觉四天怎么一下子就过去了,接着连上六天 QAQ


package string;

/**
 * @author BlackSugar
 * @date 2019/4/16
 * Implement strStr().
 * <p>
 * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
 * <p>
 * Example 1:
 * <p>
 * Input: haystack = "hello", needle = "ll"
 * Output: 2
 * Example 2:
 * <p>
 * Input: haystack = "aaaaa", needle = "bba"
 * Output: -1
 * Clarification:
 * <p>
 * What should we return when needle is an empty string? This is a great question to ask during an interview.
 * <p>
 * For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
 */
public class ImplementIndexOf {
    /**
     * 实现String indexOf方法
     * 思路:感觉这题有点。。。肯定不能直接使用内置的indexOf(),
     * 1、先求出needle的长度,再使用substring判断haystack存不存在这个自字符串并获取索引
     * 2、如果不使用所有内置方法的话,那么只能迭代了,循环判断haystack不同的头开始往后每个字符都相等
     *
     * @param haystack
     * @param needle
     * @return
     */
    public int strStr(String haystack, String needle) {
        if (null == needle || needle.length() == 0) {
            return 0;
        }
        if (null != haystack && haystack.length() > 0) {
            int length = needle.length();
            /*for (int i = 0; i <= haystack.length() - length; i++) {
                if (haystack.substring(i, i + length).equals(needle)) {
                    return i;
                }
            }*/
            for (int i = 0; i <= haystack.length() - length; i++) {
                for (int j = 0; j < length; j++) {
                    if (haystack.charAt(i + j) != needle.charAt(j)) {
                        break;
                    }
                    if (j + 1 == length) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(new ImplementIndexOf().strStr("hello", "ll"));
    }
}

总结:

今天这道题比较诡异,我们肯定不能直接使用indexOf(),感觉出题者应该是要求不用String内置方法,只能使用字符串的charAt方法,不过我这还是随便用一种吧,代码见github

1、时间复杂度O(m*n)
2、空间复杂度O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值