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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值