package LeetCodeDemo.primary;
public class Demo38 {
public static void main(String[] args){
System.out.println(new Demo38().strStr("mississippi", "issipi"));
}
public int strStr(String haystack, String needle) {
if (needle == null || needle.equals("")){
return 0;
}
if (needle.length() > haystack.length()){
return -1;
}
int start = 0;
int i = 0;
int j = 0;
char[] arr1 = haystack.toCharArray();
char[] arr2 = needle.toCharArray();
while (start < haystack.length() && j < needle.length() ){
if ( i < haystack.length() && arr1[i] == arr2[j]){ //匹配则都都加一
i++;
j++;
}else {
j = 0;
start++; // 不匹配 的情况下 重新比较即可 起始位置加一重新比较
i = start;
}
}
if (j != arr2.length){ //不存在匹配串
return -1;
}
return i - j; // 存在匹配串直接这样就行
}
}
实现strStr()
最新推荐文章于 2025-03-22 08:57:15 发布