28. 实现strStr()
题目
题解
代码
import java.util.*;
public class code28 {
// public static int strStr(String haystack, String needle) {
// return haystack.indexOf(needle);
// }
// public static int strStr(String haystack, String needle) {
// int n1 = haystack.length();
// int n2 = needle.length();
// if (n1 < n2) {
// return -1;
// } else if (n2 == 0) {
// return 0;
// }
// for (int i = 0; i < n1 - n2 + 1; i++) {
// if (haystack.substring(i, i + n2).equals(needle)) {
// return i;
// }
// }
// return -1;
// }
public static int strStr(String haystack, String needle) {
int len1 = haystack.length();
int len2 = needle.length();
if (len1 < len2) {
return -1;
} else if (len2 == 0) {
return 0;
}
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
if (j == len2) {
return i - j;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入haystack字符串: ");
String haystack = sc.nextLine();
System.out.print("请输入needle字符串: ");
String needle = sc.nextLine();
int ans = strStr(haystack, needle);
System.out.println(ans);
}
}