Update 0028.实现strStr.md

This commit is contained in:
kkkkevx
2024-03-14 11:27:41 -07:00
committed by GitHub
parent c342d7e2c1
commit 8ba68a4d6f

View File

@ -564,6 +564,38 @@ public:
## 其他语言版本
### Java
```Java
class Solution {
/**
牺牲空间,换取最直白的暴力法
时间复杂度 O(n * m)
空间 O(n + m)
*/
public int strStr(String haystack, String needle) {
// 获取 haystack 和 needle 的长度
int n = haystack.length(), m = needle.length();
// 将字符串转换为字符数组,方便索引操作
char[] s = haystack.toCharArray(), p = needle.toCharArray();
// 遍历 haystack 字符串
for (int i = 0; i < n - m + 1; i++) {
// 初始化匹配的指针
int a = i, b = 0;
// 循环检查 needle 是否在当前位置开始匹配
while (b < m && s[a] == p[b]) {
// 如果当前字符匹配,则移动指针
a++;
b++;
}
// 如果 b 等于 m说明 needle 已经完全匹配,返回当前位置 i
if (b == m) return i;
}
// 如果遍历完毕仍未找到匹配的子串,则返回 -1
return -1;
}
}
```
```Java
class Solution {