leetcode Implement strStr()题解

题目描述:Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

中文理解:实现获取某一字符串needle 在给定字符串haystack的起始下标,如aaa在aabaaa的起始下标为3。同时尽量不要使用java或者c++已有的函数来实现。

解题思路:可以可以首先根据needle和haystack的长度来进行分类,若needle为空则返回0;若needle长度大于haystack返回-1;若长度相等且字符串相等,则返回0;否则haystack长度大于needle,则在haystack从下表为0开始遍历直到最后一个可以构成needle长度的下标截止,判断从该下标取出的字符串是否等于needle,等则返回该下标,否则继续。最后返回-1;

代码(java):

class Solution {
    public int strStr(String haystack, String needle) {
        int haystackLength=haystack.length();
        int needleLength=needle.length();
        if (needleLength==0)return 0;
        if (haystackLength<needleLength)return -1;
        else if (haystackLength==needleLength && haystack.equals(needle))return 0;
        else{
            for(int i=0;i<=haystackLength-needleLength;i++){
                if(haystack.substring(i,i+needleLength).equals(needle)){
                    return i;
                }
            }
        }
        return -1;
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值