这种题目主要是各种边界条件的处理。首先是没有考虑输入是“”和“”的情况,另外没有考虑长度很长的情况下的会超时。所以又加上了字符串长度的判断。
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (haystack == NULL || needle == NULL) {
return NULL;
}
char* tempHaystack = haystack;
char* tempNeedle = needle;
int lengthHaystack = 0;
int lengthNeedle = 0;
while (*tempHaystack++ != '\0') {
++lengthHaystack;
}
while (*tempNeedle++ != '\0') {
++lengthNeedle;
}
do {
char* tempHaystack = haystack;
char* tempNeedle = needle;
while (*tempNeedle != '\0') {
if (*tempNeedle == *tempHaystack){
++tempNeedle;
++tempHaystack;
}
else {
break;
}
}
if (*tempNeedle == '\0') {
return haystack;
}
else {
++haystack;
--lengthHaystack;
}
} while (*haystack != '\0' && lengthHaystack >= lengthNeedle);
return NULL;
}
};