[leetCode]28.实现 strStr()

在这里插入图片描述

解法一 滑动窗口

新建一个与needle字符串等长的窗口,从haystack头部开始滑动,逐一匹配,匹配成功则返回下标。
在这里插入图片描述

class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int L = needle.length();
        if(L == 0 )return 0;
        if( n < L)return -1;
        for(int i = 0; i < n - L + 1; i++){
        /**
            int count = 0;
            for(int j = i; j < L + i; j++){
                if(haystack.charAt(j)!=needle.charAt(j-i))
                    break;
                else{
                    count++;
                }
            }
            if(count == needle.length())return i;
        **/
        //直接使用substring
            if(haystack.substring(i,i + L).equals(needle))return i;
        }
        return -1;
    }
}

解法二 双指针

  • 移动pn指针需要needle字符串首字符第一次出现的位置
  • 使用pn、pl、curLen从该位置开始匹配字符串needle
  • 长度匹配成功则返回匹配字符串首字符位置:pn - L
  • 匹配不成功则回溯pn = pn - curLen + 1; pl = 0, curLen = 0
class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int L = needle.length();
        if(L == 0 )return 0;
        if( n < L)return -1;
        int pn = 0;//指向haystack的指针pn
        while(pn < n - L + 1){
            //用pn在haytack中找到needle字符串首字符出现的位置
            while(pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) pn++;
            int curLen = 0, pl = 0;
            while(pn < n && pl < L && haystack.charAt(pn)==needle.charAt(pl)){
                ++pl;
                ++pn;
                ++curLen;
            }
            //整个needle匹配成功返回匹配子串开始的位置
            if(curLen == L) return pn - L;
            //匹配不成功则讲pn回溯
            pn  = pn - curLen + 1;
        }
        return -1;
    }
}
posted @ 2020-06-22 10:21  消灭猕猴桃  阅读(55)  评论(0编辑  收藏  举报