题目:
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
.
Do I need to implement KMP Algorithm in a real interview?
If source = "source"
and target = "target"
, return -1
.
If source = "abcdabcdefg"
and target = "bcd"
, return 1
.
题解:
Solution 1 ()
class Solution { public: int strStr(const char *source, const char *target) { if (source == NULL || target == NULL) { return -1; } int len1 = strlen(source); int len2 = strlen(target); for (int i = 0, j = 0; i < len1 - len2 + 1; i++) { for (j = 0; j < len2; j++) { if (source[i + j] != target[j]) { break; } } if (j == len2) { return i; } } return -1; } };
原文:http://www.cnblogs.com/Atanisi/p/6953832.html