地址: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 Nonedef strStr(self, haystack, needle):if haystack == needle:return needleh = len(haystack)n = len(needle)if not haystack or not needle or h < n:return None#if not needle:# return haystackfor i in range(0, h-n+1):f = Truefor j in range(0, n):if haystack[i+j] != needle[j]:f = Falsebreak;if f:return haystack[i:]return None"""