来源:Leetcode
原帖: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.
代码:
原帖: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:
int strStr(char *haystack, char *needle) {
if (!haystack || !needle) return -1;
char* h_start = haystack;
while (1) {
char *h = haystack, *n = needle;
while (*n && *h && *h == *n) {
h++; n++;
}
if (*n == '\0') return haystack - h_start; // match position
if (*h == '\0') return -1;
haystack++;
}
}
};
class Solution {
char *strStr(char *haystack, char *needle) {
if (!haystack || !needle) return NULL;
int lenHaystack = strlen(haystack);
int lenNeedle = strlen(needle);
int i, j;
for (i = 0; i <= lenHaystack - lenNeedle; ++i) {
for (j = 0; j < lenNeedle; ++j) {
if (haystack[i + j] != needle[j]) break;
}
if (j == lenNeedle) return haystack + i;
}
return NULL;
}
};
No comments:
Post a Comment