每日算法之二十四:Implement strStr()

<span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px; background-color: rgb(255, 255, 255);">Implement strStr().</span>

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.


下面是两种方法:(1)


class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(needle==NULL||*needle=='\0')
            return haystack;
        int length=(int)strlen(needle);//如果要获得长度,用strlen,否则sizeof(*needle)/sizeof(char),结果永远为固定值,因为needle参数表示的是一个指针变量,
        char* p_res=NULL;
        char* needle_start=needle;
        
        for(;*haystack!='\0';haystack++){
            if(*haystack==*needle){
                needle++;
                if(*needle=='\0')
                    break;
            }else{
                int already_len=(int)(needle-needle_start);
                if(already_len==0) {
                    continue;
                } else {
                    haystack=haystack-already_len; //回溯
                    needle=needle_start;//回溯
                }
            }
            
        }
        p_res=haystack-length+1;
        if(*needle=='\0')
            return p_res;
        else
            return NULL;
    }
};

(2)自己写的KMP,但是还有错误没有调整

class Solution {
public:
    int len(char *word)
    {
        int i = 0;
        while(*(word+i)!='\0')
        i++;
        return i;
    }
  void generateNext(char *needle,int *next,int needle_len)
  {
    next[0] = 0;
    for(int i = 1,j = 0;i<needle_len;i++)
    {
      while(j>0 && needle[i]!=needle[j])
        j = next[j-1];
      if(needle[i] = needle[j])
        j++;
      next[i] = j;
    }
  }
  char *strStr(char *haystack, char *needle) {
      int haystack_len = len(haystack);
        int needle_len = len(needle);
     if(haystack==NULL || needle == NULL || len(needle)==0)  
        return haystack;  
    if(len(needle)>len(haystack))
        return NULL; 
       
     
        
        int * next = new int[needle_len];
        generateNext(needle,next,needle_len);
        for(int i = 0,j = 0;i<haystack_len;i++)
        {
          while(j>0 && haystack[i]!=needle[j])
            j = next[j-1];
          if(haystack[i] == needle[j])
            j++;
          if(j == needle_len)
           if(j>i)
            return haystack;
            else
            return &haystack[i-j];
        }
        return NULL;
    }
};

KMP算法参考: http://blog.csdn.net/yapian8/article/details/24578465

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值