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;
        }
    }
    
  • 相关阅读:
    Apache基本设置
    主流无线传输技术GPRS与CDMA之对比
    光波分复用系统(WDM)技术要求
    IPv6报头结构以及与IPv4的比较
    网络设计师训练资料
    802.11b/11a/11g横向比较
    交换机术语
    无线局域网技术白皮书
    无线网络基础知识
    校验码
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860026.html
Copyright © 2011-2022 走看看