• Implement strStr()


    Implement strStr().

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

    class Solution {
    public:
        int strStr(char *haystack, char *needle) {
            if(!*needle) return 0;
            char *p1=haystack;
            char *p2;
            char *p1_advance=haystack;//此值用于保证haystack的剩余长度大于needle
            char *p1_old=haystack;
            p2=needle+1;//注意此处的初始值
            while(*p2!=''){
                p1_advance++;
                p2++;
            }
            for(;*p1_advance!='';p1_advance++){
                p1=p1_old;//从上次遍历起始位置的下一个字符开始
                p2=needle;
                while(*p1!=''&&*p2!=''&&*p1==*p2){
                    p1++;
                    p2++;
                }
                if(*p2=='')return p1_old-haystack;//如果needle遍历完,说明匹配成功,可返回
                p1_old++;
            }
            return -1;
            
        }
    };

    此为暴力法,复杂度O(m*n),空间复杂度为O(1)。另有KMP解法,通过计算部分匹配表优化。时间复杂度可优化为O(N+M)

  • 相关阅读:
    2019年8月20日 item系列
    变量和字符
    python命名规则
    五大常用算法之贪心算法
    过河卒
    组成三位数
    编码问题
    FatMouse' Trade
    A Boring Game
    螺旋矩阵
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4394787.html
Copyright © 2020-2023  润新知