# LeetCode力扣每日一题（Java）：28、找出字符串中第一个匹配项的下标

## 二、解题思路

### 1、我的思路

char[] ch = haystack.toCharArray();
char[] cn = needle.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(ch[i] == cn[0]){
int flag = 1;
for(int j=1;j<cn.length;j++){
if(i+j > ch.length - 1 || ch[i+j] != cn[j]){
flag = 0;
break;
}
}
if(flag == 1){
return i;
}
}
}
return -1;

### 2、官方题解

#### 方法一：暴力匹配

class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
for (int i = 0; i + m <= n; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
}

##### 方法二：Knuth-Morris-Pratt算法

class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m == 0) {
return 0;
}
int[] pi = new int[m];
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
}

THE END