LeetCode -- 28. Implement strStr()
Posted feliz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode -- 28. Implement strStr()相关的知识,希望对你有一定的参考价值。
My solution:
class Solution { public: int strStr(string haystack, string needle) { int hsize = haystack.size(); int nsize = needle.size(); if(hsize<nsize) return -1; if(needle == "" ||haystack == "") return 0; for(int i=0; i<hsize; i++){ if(haystack[i] == needle[0]){ for(int j=1; j<nsize; j++){ if(haystack[i+j] != needle[j]) break; if(j == nsize-1) return i; } if(nsize == 1) return i; } } return -1; } };
Other guy‘s solution
int strStr(string haystack, string needle) { if(haystack.size() < needle.size()) return -1; int index = 0; int i,j; for(i = 0, j = 0;i < haystack.size() && j < needle.size();){ if(haystack[i] == needle[j]){ i++; j++; }else{ index++; i = index; j = 0; } } if(j == needle.size()) return index; return -1; }
以上是关于LeetCode -- 28. Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode---28. Implement strStr()
44. leetcode 28. Implement strStr()
leetcode 28. Implement strStr()
LeetCode OJ 28Implement strStr()