Skip to content

Commit e7fea38

Browse files
committed
opt: opt 028
1 parent 50a8e76 commit e7fea38

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

note/028/README.md

+8-6
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,20 @@ Returns the index of the first occurrence of needle in haystack, or -1 if needle
1111

1212
## 思路
1313

14-
题意是从主串中找到子串的索引,如果找不到则返回-1,我们只需要遍历主串长度减子串长度即可,利用substring比较即可
14+
题意是从主串中找到子串的索引,如果找不到则返回-1,当字串长度大于主串,直接返回-1,然后我们只需要遍历比较即可
1515

1616
```java
1717
class Solution {
1818
public int strStr(String haystack, String needle) {
19-
int l1 = haystack.length(), l2 = needle.length(), l3 = l1 - l2;
20-
for (int i = 0; i <= l3; ++i) {
21-
if (haystack.substring(i, i + l2).equals(needle)) {
22-
return i;
19+
int l1 = haystack.length(), l2 = needle.length();
20+
if (l1 < l2) return -1;
21+
for (int i = 0; ; i++) {
22+
for (int j = 0; ; j++) {
23+
if (j == l2) return i;
24+
if (i + j == l1) return -1;
25+
if (haystack.charAt(i + j) != needle.charAt(j)) break;
2326
}
2427
}
25-
return -1;
2628
}
2729
}
2830
```

src/com/blankj/easy/_028/Solution.java

+7-5
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
*/
1111
public class Solution {
1212
public int strStr(String haystack, String needle) {
13-
int l1 = haystack.length(), l2 = needle.length(), l3 = l1 - l2;
14-
for (int i = 0; i <= l3; ++i) {
15-
if (haystack.substring(i, i + l2).equals(needle)) {
16-
return i;
13+
int l1 = haystack.length(), l2 = needle.length();
14+
if (l1 < l2) return -1;
15+
for (int i = 0; ; i++) {
16+
for (int j = 0; ; j++) {
17+
if (j == l2) return i;
18+
if (i + j == l1) return -1;
19+
if (haystack.charAt(i + j) != needle.charAt(j)) break;
1720
}
1821
}
19-
return -1;
2022
}
2123

2224
public static void main(String[] args) {

0 commit comments

Comments
 (0)