File tree 1 file changed +32
-0
lines changed
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -564,6 +564,38 @@ public:
564
564
## 其他语言版本
565
565
566
566
### 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
+ ```
567
599
568
600
``` Java
569
601
class Solution {
You can’t perform that action at this time.
0 commit comments