您的位置:首页 > 其它

LeetCode: Implement strStr()

2013-03-21 15:32 337 查看
可以用c的方法

class Solution {
public:
char *strStr(char *haystack, char *needle) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int haylen = strlen(haystack);
int needlen = strlen(needle);
for (int i = 0; i <= haylen-needlen; i++) {
char *p = haystack + i;
char *q = needle;
while (*q != '\0' && *p == *q) {
p++, q++;
}
if (*q == '\0') return haystack + i;
}
return NULL;
}
};


再贴段更加清晰的代码

class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string S, T;
for (int i = 0; *(haystack+i) != '\0'; i++) S += *(haystack+i);
for (int i = 0; *(needle+i) != '\0'; i++) T += *(needle+i);
int m = S.size();
int n = T.size();
if (!n) return haystack;
for (int i = 0; i < m-n+1; i++) {
if (S.substr(i, n) == T) return haystack+i;
}
return NULL;
}
};


public class Solution {
public int StrStr(string haystack, string needle) {
if (needle.Length == 0) return 0;
for (int i = 0; i < haystack.Length - needle.Length + 1; i++) {
if (haystack.Substring(i, needle.Length) == needle) return i;
}
return -1;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: