Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8ba68a4

Browse files
authored
Update 0028.实现strStr.md
1 parent c342d7e commit 8ba68a4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎problems/0028.实现strStr.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,38 @@ public:
564564
## 其他语言版本
565565

566566
### Java:
567+
```Java
568+
class Solution {
569+
/**
570+
牺牲空间,换取最直白的暴力法
571+
时间复杂度 O(n * m)
572+
空间 O(n + m)
573+
*/
574+
public int strStr(String haystack, String needle) {
575+
// 获取 haystack 和 needle 的长度
576+
int n = haystack.length(), m = needle.length();
577+
// 将字符串转换为字符数组,方便索引操作
578+
char[] s = haystack.toCharArray(), p = needle.toCharArray();
579+
580+
// 遍历 haystack 字符串
581+
for (int i = 0; i < n - m + 1; i++) {
582+
// 初始化匹配的指针
583+
int a = i, b = 0;
584+
// 循环检查 needle 是否在当前位置开始匹配
585+
while (b < m && s[a] == p[b]) {
586+
// 如果当前字符匹配,则移动指针
587+
a++;
588+
b++;
589+
}
590+
// 如果 b 等于 m,说明 needle 已经完全匹配,返回当前位置 i
591+
if (b == m) return i;
592+
}
593+
594+
// 如果遍历完毕仍未找到匹配的子串,则返回 -1
595+
return -1;
596+
}
597+
}
598+
```
567599

568600
```Java
569601
class Solution {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /