*Leetcode_implement-strstr

62 篇文章 0 订阅
52 篇文章 0 订阅

地址:http://oj.leetcode.com/problems/implement-strstr/

Implement strStr().

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

思路:先根据指针为空或者长度条件预处理,再逐位比。常考的基础题,要多练习。

参考代码:

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(!needle || !haystack || strlen(needle)>strlen(haystack))
            return NULL;

        for(int i = 0; i <= strlen(haystack) - strlen(needle); ++i)
        {
            bool flag = true;
            for(int j = 0; j < strlen(needle); ++j)
            {
                 if(needle[j] != haystack[i+j])
                 {
                     flag = false;
                     break;
                 }
            }
            if(flag)
                return haystack+i;
        }
        return NULL;
    }
};

//SECOND TRIAL, 8MS

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        int len1 = strlen(haystack), len2 = strlen(needle);
        if(!haystack || !needle || len1 < len2)
            return NULL;
        for(int i = 0; i<= len1-len2; ++i)
        {
            int j = 0;
            for(; j<len2; ++j)
            {
                if(*(haystack+i+j) != *(needle+j))
                    break;
            }
            if(j==len2)
                return haystack+i;
        }
        return NULL;
    }
};

python version:

class Solution:
    # @param haystack, a string
    # @param needle, a string
    # @return a string or None
    def strStr(self, haystack, needle):
        if haystack == needle:
            return needle
        h = len(haystack)
        n = len(needle)
        if not haystack or h < n:
            return None
        if not needle:
            return haystack
        for i in range(0, h-n+1):
            f = True
            for j in range(0, n):
                if haystack[i+j] != needle[j]:
                    f = False
                    break;
            if f:
                return haystack[i:]
        return None

 
 
#python的测试集不一样?写成下面的会有错误,这个不应该返回NULL么
#Input: "a", ""
#Output: null
#Expected: "a"
 
 
# WA 代码
"""
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
if haystack == needle:
return needle
h = len(haystack)
n = len(needle)
if not haystack or not needle or h < n:
return None
#if not needle:
# return haystack
for i in range(0, h-n+1):
f = True
for j in range(0, n):
if haystack[i+j] != needle[j]:
f = False
break;
if f:
return haystack[i:]
return None
"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值