LeetCode-Implement strStr()

Implement strStr().

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

简单暴力

[Code]

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(haystack == NULL || needle == NULL)
            return NULL;
        int hLen = strlen(haystack);
        int nLen = strlen(needle);
        if(hLen < nLen)
            return NULL;
        if(nLen == 0) //"", ""   return ""
            return haystack;
        for(int i=0;i < hLen-nLen+1; i++){//只要循环hLen-nLen+1次,因为这之后主串的位数少于nLen,也就不可能找到子串了
            int index = i;
            int j = 0;
            while(j < nLen && haystack[index] == needle[j]){
                j++;
                index++;
            }
            if(j == nLen)
                return haystack+i;
        }
        return NULL;
    }
};

如果不允许用strlen等库函数,可采用以下代码

char* StrStr(const char *str, const char *target) {
  if (!*target) return str;
  char *p1 = (char*)str, *p2 = (char*)target;
  char *p1Adv = (char*)str;
  while (*++p2)
    p1Adv++;
  while (*p1Adv) {
    char *p1Begin = p1;
    p2 = (char*)target;
    while (*p1 && *p2 && *p1 == *p2) {
      p1++;
      p2++;
    }
    if (!*p2)
      return p1Begin;
    p1 = p1Begin + 1;
    p1Adv++;
  }
  return NULL;
}


你可能感兴趣的:(LeetCode,strstr)