Leetcode Implement strStr() My Submissions

本文详细解析了如何实现strStr()函数,该函数用于在haystack字符串中查找首次出现needle字符串的位置。文章讨论了多种特殊情况,例如needle为空或其长度大于haystack的情况,并提供了一段完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement strStr()

  My Submissions

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

这个题没点难度,但是考虑得不够全,提交了好几次.

坑有这么几个:

1.needle可能啥也没有.

2.可能needle 的长度大于 haystack

3.可以走着走着到最后了.

说白了,关键还是长度,长度,长度....


public class Solution {
    public String strStr(String haystack, String needle) {
        if (haystack == null){
            return null;
        }
        if (needle == null || needle.equals("")){
            return haystack;
        }
        if (needle.length() > haystack.length()){
            return null;
        }
        int leng = 0;
        for (int i = 0; i < haystack.length(); i++){
            if (needle.charAt(0) == haystack.charAt(i)){
                leng = needle.length() - 1;
                for (int j = 1; j < needle.length(); j++){
                    if (i + j > haystack.length() - 1){
                        return null;
                    }
                    if (needle.charAt(j) == haystack.charAt(i + j)){
                        leng--;
                    }
                }
                if (leng == 0){
                    return haystack.substring(i);
                }
            }
        }
        return null;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值