[Leetcode] Implement strStr()

Implement strStr().

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

方法1:利用系统方法String.indexOf(),耗时6ms

public class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}



方法2:自己写方法,耗时12ms,还不清楚可以怎么优化,可以看看官方怎么实现String.indexOf()方法的

public class Solution {
    public int strStr(String haystack, String needle) {
        int i=0;   //haystack的指针
        int j=0;   //needle的指针
        int len1=haystack.length();
        int len2=needle.length();
        int lastIndex=0;  //上一个开始匹配的地方
        boolean flag=false;    //前一个是对是错
        if(len2<1) return 0;
        if(len1<1) return -1;
        while(i<len1&&j<len2)
        {
            if(haystack.charAt(i)==needle.charAt(j)) 
            {
                if(j==(len2-1)) return i-j;   //完全匹配
                j++;                          
                if(flag==false) lastIndex=i;   
                flag=true;
            }
            else
            {
                if(flag) i=lastIndex;//匹配不成功,返回到上一个开始匹配的地方
                else lastIndex++;
                j=0;
                flag=false;
            }
            i++;
        }
        return -1;

    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值