mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0028.实现strStr.md
添加 0028.实现strStr Java版本,基于滑动窗口的算法
This commit is contained in:
@ -565,6 +565,54 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
```Java
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* 基于窗口滑动的算法
|
||||||
|
* <p>
|
||||||
|
* 时间复杂度:O(m*n)
|
||||||
|
* 空间复杂度:O(1)
|
||||||
|
* 注:n为haystack的长度,m为needle的长度
|
||||||
|
*/
|
||||||
|
public int strStr(String haystack, String needle) {
|
||||||
|
int m = needle.length();
|
||||||
|
// 当 needle 是空字符串时我们应当返回 0
|
||||||
|
if (m == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int n = haystack.length();
|
||||||
|
if (n < m) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int i = 0;
|
||||||
|
int j = 0;
|
||||||
|
while (i < n - m + 1) {
|
||||||
|
// 找到首字母相等
|
||||||
|
while (i < n && haystack.charAt(i) != needle.charAt(j)) {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i == n) {// 没有首字母相等的
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
// 遍历后续字符,判断是否相等
|
||||||
|
i++;
|
||||||
|
j++;
|
||||||
|
while (i < n && j < m && haystack.charAt(i) == needle.charAt(j)) {
|
||||||
|
i++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (j == m) {// 找到
|
||||||
|
return i - j;
|
||||||
|
} else {// 未找到
|
||||||
|
i -= j - 1;
|
||||||
|
j = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```java
|
```java
|
||||||
// 方法一
|
// 方法一
|
||||||
class Solution {
|
class Solution {
|
||||||
|
Reference in New Issue
Block a user