对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。若是不存在,则返回 -1
。面试
在面试中我是否须要实现KMP算法?算法
若是 source = "source"
和 target = "target"
,返回 -1
。测试
若是 source = "abcdabcdefg"
和 target = "bcd"
,返回 1
。spa
/*
思路:
我以前想的是若是匹配,子串和母串同时移动,若是不匹配,子串返回首位置,母串继续移动,可是就是这出错了,,,好比acactor 和 actor 匹配时,应该进一步修改细节,若是不匹配,这时候若是是由于子串首字母都不匹配,那么原思路是正确的,可是若是匹配了一半不匹配了,此时母串不该该向后移动的。即i++.
*/
class Solution {
public int strStr(String source, String target) {
// write your code here
if (source == null || target == null || source.length()< target.length()) {
return -1;
}
if (target.length() == 0) {
return 0;
}
int i = 0,j = 0;
//循环,true控制
while (true) {
if (source.charAt(i) == target.charAt(j)) {//一个个遍历
j++;//相同都加1
i++;
} else {
//一开始就不相同的话,母串++移动
if(j ==0){
i++;
}
//可是若是匹配了一半不匹配了,此时母串不该该向后移动的。
//只有目标子串从头开始,
j = 0;
//不判断的话,例如"tartarget""target"
}
//若是子串所有匹配
if (j == target.length()) {
return i - j;
}
//若是母串已经到尾,退出循环
if (i == source.length()) {
break;
}
}
return -1;
}
}
code