strStr2
原文首发自heliuphy的博客
题目描述
实现时间复杂度为 O(n + m)的方法 strStr。 strStr 返回目标字符串在源字符串中第一次出现的第一个字符的位置. 目标字串的长度为 m , 源字串的长度为 n . 如果目标字串不在源字串中则返回 -1。
样例
输入:source = "abcdef", target = "bcd"
输出:1
解释:
字符串第一次出现的位置为1。
代码
public class Solution {
/*
* @param source: A source string
* @param target: A target string
* @return: An integer as index
*/
public int strStr2(String source, String target) {
// write your code here
if (source == null || target == null) {
return -1;
}
int m = target.length();
int n = source.length();
if (m == 0 && source != null) {
return 0;
}