mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2478 from kkkkevx/master
Update 0028.实现strStr.md java 提供一个更直白的暴力法
This commit is contained in:
@ -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 {
|
||||
|
Reference in New Issue
Block a user