题目:
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
.
Clarification
Do I need to implement KMP Algorithm in a real interview?
- Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure your confirm with the interviewer first.
Example
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; } };
时间: 2024-10-24 21:08:11