LeetCode: Implement strStr()
2013-03-21 15:32
337 查看
可以用c的方法
再贴段更加清晰的代码
View Code
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
相关文章推荐
- LeetCode:Implement strStr()
- LeetCode:Implement strStr()
- [leetcode] Implement strStr()
- 【LEETCODE】Implement strStr().
- LeetCode (28)Implement strStr()
- leetcode 28:Implement strStr()
- Leetcode: Implement strStr()
- [LeetCode28] Implement strStr()
- leetcode---Implement strStr()
- [Leetcode] Implement strStr() (Java)
- 和大神们学习每天一题(leetcode)-Implement strStr()
- Leetcode 28 Implement strStr()
- LeetCode(28) Implement strStr()
- Leetcode Implement strStr()解题报告
- [LeetCode] 034: Implement strStr()
- LeetCode Implement strStr()
- leetcode(57)- Implement strStr()
- 【leetcode】3.2 Implement strStr()
- [leetcode] Implement strStr()
- [LeetCode] Implement strStr()