找出字符串中第一个匹配项的下标
题目详解
28. 找出字符串中第一个匹配项的下标
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:”sad” 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = “leetcode”, needle = “leeto”
输出:-1
解释:”leeto” 没有在 “leetcode” 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 仅由小写英文字符组成
题解
暴力求解发
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public static int strStr(String haystack, String needle) { char[] haystackArray = haystack.toCharArray(); char[] needleArray = needle.toCharArray(); if (needleArray.length == 0) { return 0; } if (haystackArray.length == needleArray.length && needle.equals(haystack)) { return 0; } if (needleArray.length > haystackArray.length) { return -1; } int index = -1;
for (int i = 0; i < haystackArray.length; i++) { int littleIndex = i; if (littleIndex > haystackArray.length - needleArray.length) { return -1; } for (int j = 0; j < needleArray.length; j++) { if (haystackArray[littleIndex] == needleArray[j]) { if (j == 0) { index = littleIndex; } littleIndex++; if (j == needleArray.length-1) { return index; } }else { break; } } } return index; }
|

KMP解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public int strStr(String ss, String pp) { if (pp.isEmpty()) return 0; int n = ss.length(), m = pp.length(); ss = " " + ss; pp = " " + pp;
char[] s = ss.toCharArray(); char[] p = pp.toCharArray();
int[] next = new int[m + 1]; for (int i = 2, j = 0; i <= m; i++) { while (j > 0 && p[i] != p[j + 1]) j = next[j]; if (p[i] == p[j + 1]) j++; next[i] = j; }
for (int i = 1, j = 0; i <= n; i++) { while (j > 0 && s[i] != p[j + 1]) j = next[j]; if (s[i] == p[j + 1]) j++; if (j == m) return i - m; }
return -1; } }
|

解析:todo 最近有点忙,过了这阵子再写,嘻嘻😁