LeetCode 经典 150 · 可视化
逐步动画、变量流转与五语言代码参考
#28 · 数组 / 字符串
找出字符串中第一个匹配项的下标
Find the Index of the First Occurrence in a String
haystack = "sadbutsad", needle = "sad"线性序列3 个关键状态
步骤 1先为 needle 构建最长前后缀表。
lps=[0,0,0]s
0a
1d
2推荐
KMP 前缀函数
时间
O(n+m)空间 O(m)失配时利用模式串已知的相同前后缀跳转,不回退文本指针。
1function strStr(h, p) {2 const lps = Array(p.length).fill(0);3 for (let i = 1, j = 0; i < p.length;) {4 if (p[i] === p[j]) lps[i++] = ++j;5 else if (j) j = lps[j - 1];6 else i++;7 }8 for (let i = 0, j = 0; i < h.length;) {9 if (h[i] === p[j]) {10 i++;11 j++;12 if (j === p.length) return i - j;13 } else if (j) j = lps[j - 1];14 else i++;15 }16 return -1;17}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class Solution {2 public int strStr(String haystack, String needle) {3 if ("".equals(needle)) {4 return 0;5 }6 7 int len1 = haystack.length();8 int len2 = needle.length();9 int p = 0;10 int q = 0;11 while (p < len1) {12 if (haystack.charAt(p) == needle.charAt(q)) {13 if (len2 == 1) {14 return p;15 }16 ++p;17 ++q;18 } else {19 p -= q - 1;20 q = 0;21 }22 23 if (q == len2) {24 return p - q;25 }26 }27 return -1;28 }29}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。