strStr解题报告

Description:

For a given source string and a target string, you should output the first index(from 0) of target string in source string.

If target does not exist in source, just return -1.

Example:

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

Link:

http://www.lintcode.com/en/problem/strstr/#

Time Complexity:

O(N^2)

完整代码:

int strStr(const char *source, const char *target) { if(source == NULL || target == NULL) //要写在最前面,不然当source为NULL时,s-t会导致死循环 return -1; int s = strlen(source), t = strlen(target); int i, j; for(i = 0; i <= s - t; i++) { for(j = 0; j < t; j++) if(source[i+j] != target[j]) break; if(j == t) //j == t而不是j == t-1 return i; } return -1; }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容