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; }