File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change 6666 - [ 数组中的最长山脉(Longest Mountain in Array)(反向双指针)] ( #数组中的最长山脉longest-mountain-in-array反向双指针 )
6767 - [ 最长回文子串(Longest Palindromic Substring)] ( #最长回文子串longest-palindromic-substring )
6868- [ 分离双指针] ( #分离双指针 )
69+ - [ 实现 strstr()] ( #实现-strstr )
6970 - [ 两个数组的交集(Intersection of Two Arrays)] ( #两个数组的交集intersection-of-two-arrays )
7071 - [ I] ( #i )
7172 - [ II] ( #ii )
@@ -1173,6 +1174,71 @@ class Solution:
11731174
11741175# 分离双指针
11751176
1177+ ## 实现 strstr()
1178+ > LeetCode/[ 28. 实现strStr()] ( https://leetcode-cn.com/problems/implement-strstr/description/ )
1179+
1180+ ** 问题描述**
1181+ ```
1182+ 实现 strStr() 函数。
1183+
1184+ 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
1185+
1186+ 示例 1:
1187+ 输入: haystack = "hello", needle = "ll"
1188+ 输出: 2
1189+ 示例 2:
1190+ 输入: haystack = "aaaaa", needle = "bba"
1191+ 输出: -1
1192+ 说明:
1193+
1194+ 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
1195+
1196+ 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
1197+ ```
1198+
1199+ ** 思路**
1200+ - 模式匹配,常见的高效算法有 KMP 算法和 Karp-Rabin(KR)算法
1201+ > [ 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法 - 单车博客园] ( https://www.cnblogs.com/dancheblog/p/3517338.html ) - 博客园
1202+ - 这里只介绍双指针方法 ` O(nm) ` 和 Karp-Rabin 算法 ` O(n+m) `
1203+
1204+ ** 双指针**
1205+ ``` python
1206+ class Solution :
1207+ def strStr (self , S , T ):
1208+ """
1209+ :type S: str
1210+ :type T: str
1211+ :rtype: int
1212+ """
1213+ if not T: # 如果 T 为空,返回 0,与 C++/Java 行为一致
1214+ return 0
1215+
1216+ n = len (S)
1217+ m = len (T)
1218+
1219+ ans = - 1 # 不存在返回 -1
1220+ found = 0
1221+ for i in range (n - m + 1 ):
1222+ for j in range (m):
1223+ if S[i + j] != T[j]:
1224+ break
1225+
1226+ if j == m - 1 :
1227+ ans = i
1228+ found = 1
1229+
1230+ if found:
1231+ break
1232+
1233+ return ans
1234+ ```
1235+
1236+ ** KR 算法**
1237+ ``` python
1238+
1239+ ```
1240+
1241+
11761242## 两个数组的交集(Intersection of Two Arrays)
11771243
11781244### I
You can’t perform that action at this time.
0 commit comments