Movatterモバイル変換


[0]ホーム

URL:


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

Commite7fea38

Browse files
committed
opt: opt 028
1 parent50a8e76 commite7fea38

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

‎note/028/README.md

Lines changed: 8 additions & 6 deletions
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
classSolution {
1818
publicintstrStr(Stringhaystack,Stringneedle) {
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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
*/
1111
publicclassSolution {
1212
publicintstrStr(Stringhaystack,Stringneedle) {
13-
intl1 =haystack.length(),l2 =needle.length(),l3 =l1 -l2;
14-
for (inti =0;i <=l3; ++i) {
15-
if (haystack.substring(i,i +l2).equals(needle)) {
16-
returni;
13+
intl1 =haystack.length(),l2 =needle.length();
14+
if (l1 <l2)return -1;
15+
for (inti =0; ;i++) {
16+
for (intj =0; ;j++) {
17+
if (j ==l2)returni;
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
publicstaticvoidmain(String[]args) {

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp