每日算法之二十四: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

你可能感兴趣的:(查找)