File tree 2 files changed +3
-3
lines changed
2 files changed +3
-3
lines changed Original file line number Diff line number Diff line change @@ -25,17 +25,17 @@ Tags:** Two Pointers, String
25
25
26
26
## 思路
27
27
28
- 题意是从主串中找到子串的索引,如果找不到则返回-1,当字串长度大于主串 ,直接返回-1,然后我们只需要遍历比较即可。
28
+ 题意是从主串中找到子串的索引,如果找不到则返回-1,当子串长度大于主串 ,直接返回-1,然后我们只需要遍历比较即可。
29
29
30
30
``` java
31
31
class Solution {
32
32
public int strStr (String haystack , String needle ) {
33
33
int l1 = haystack. length(), l2 = needle. length();
34
34
if (l1 < l2) return - 1 ;
35
35
for (int i = 0 ; ; i++ ) {
36
+ if (i + l2 > l1) return - 1 ;
36
37
for (int j = 0 ; ; j++ ) {
37
38
if (j == l2) return i;
38
- if (i + j == l1) return - 1 ;
39
39
if (haystack. charAt(i + j) != needle. charAt(j)) break ;
40
40
}
41
41
}
Original file line number Diff line number Diff line change @@ -13,9 +13,9 @@ public int strStr(String haystack, String needle) {
13
13
int l1 = haystack .length (), l2 = needle .length ();
14
14
if (l1 < l2 ) return -1 ;
15
15
for (int i = 0 ; ; i ++) {
16
+ if (i + l2 > l1 ) return -1 ;
16
17
for (int j = 0 ; ; j ++) {
17
18
if (j == l2 ) return i ;
18
- if (i + j == l1 ) return -1 ;
19
19
if (haystack .charAt (i + j ) != needle .charAt (j )) break ;
20
20
}
21
21
}
You can’t perform that action at this time.
0 commit comments