Lintcode013.strStr
Posted Vincent丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode013.strStr相关的知识,希望对你有一定的参考价值。
题目:
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; } };
以上是关于Lintcode013.strStr的主要内容,如果未能解决你的问题,请参考以下文章