对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
。
在面试中我是否需要实现KMP算法?
- 不需要,当这种问题出现在面试中时,面试官很可能只是想要测试一下你的基础应用能力。当然你需要先跟面试官确认清楚要怎么实现这个题。
如果 source = "source"
和
target = "target"
,返回 -1
。
如果 source = "abcdabcdefg"
和
target = "bcd"
,返回 1
。
/*
思路:
我之前想的是如果匹配,子串和母串同时移动,如果不匹配,子串返回首位置,母串继续移动,但是就是这出错了,,,比如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;
}
}