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.

本以为很复杂,没想到brute force一遍就过了。其实这个题有些高级的算法可以应用,such as KMP,不过面试中不太可能出现。

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if (haystack == NULL || needle == NULL) {
            return NULL;
        }
        
        int hsize = 0, nsize = 0;
        for (char *tmp = haystack; *tmp != 0; ++tmp) {
            ++hsize;
        }
        for (char *tmp = needle; *tmp != 0; ++tmp) {
            ++nsize;
        }
        if (hsize < nsize) {
            return NULL;
        }
        
        char *start = NULL;
        char *match = NULL;
        for (int i = 0; i <= hsize - nsize; ++i) {
            start = haystack + i;
            match = needle;
            while (*match != 0 && *start == *match) {
                ++start;
                ++match;
            }
            if (*match == 0) {
                return (haystack + i);
            }
        }
        
        return NULL;
    }
};

=================第二次=================

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        if (haystack == NULL || needle == NULL) {
            return -1;
        }
        
        int max_index = strlen(haystack) - strlen(needle);
        for (int i = 0; i <= max_index; ++i) {
            char *start = haystack + i;
            char *target = needle;
            while (*target != '\0' && *start == *target) {
                ++start;
                ++target;
            }
            if (*target == '\0') {
                return i;
            }
        }
        
        return -1;
    }
};


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