zoukankan      html  css  js  c++  java
  • [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;
        }
    }
    
  • 相关阅读:
    操作系统设计与实现 读笔(2)
    操作系统设计与实现 读笔(1)
    C++历史及优点
    套接字Socket——TCP、UDP通信
    Unix环境_进程管理
    Unix环境_信号处理机制
    排序算法汇总
    TCP/IP体系结构
    数据库模式——三级模式两级映像
    杨辉三角形的递归实现
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860026.html
Copyright © 2011-2022 走看看