28. 实现 strStr()

思路:
1.两个字符串分别定义一个从头开始的指针,并且同时从左向右遍历字符串。
2.如果发现两个指针指向的字符是相同,则 f l a g flag flag记录当前的left值,继续同时向右遍历,如果直到 n e e d l e needle needle遍历结束,都相同,则说明存在 h a y s t a c k haystack haystack存在 n e e d l e needle needle,则 f l a g flag flag值就是首先出现的索引位置。如果在 n e e d l e needle needle遍历结束前发现存在不同的字符,则left指针重新指向 f l a g + 1 flag+1 flag+1出, r i g h t right right重新指向第二个字符串的开始,并且将 f l a g flag flag置为-1,再次遍历,。

class Solution {
    public int strStr(String haystack, String needle) {
        int left = 0;
        int right = 0;
        int flag = -1;
        while((right <= needle.length() - 1 && left <= haystack.length() - 1)||(right==0 && left <= haystack.length() - needle.length()) ){
            if(haystack.charAt(left) == needle.charAt(right)){
                if(flag == -1)
                    flag = left;
                left++;
                right++;
            }
            else {
                if(flag != -1){
                    left = flag + 1;
                    right  = 0;
                    flag = -1;
                }
                else
                left++;
            }
        }
        if(right == needle.length())
            return flag;
        return -1;
    }
}

KMP算法,时间复杂度会更低。

class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length(),m = needle.length();
        if(m == 0)
            return 0;
        int next[] = new int[m];
        next[0] = 0;
        int i = 0;
        for (int j = 1; j < m; j++) {
            while (i > 0 && needle.charAt(j) != needle.charAt(i))
                i = next[i - 1];
            if(needle.charAt(j) == needle.charAt(i))
                i++;
            next[j] = i;
        }
        int j = 0;
        for (i = 0; i < n; i++) {
            while(j > 0 && needle.charAt(j) != haystack.charAt(i))
                j = next[j - 1];
            if(needle.charAt(j) == haystack.charAt(i))
                j++;
            if(j == m)
                return i - m +1;
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值