File tree 3 files changed +69
-0
lines changed
project/LeetCode/leetcode/src/main/java/com/blankj/easy/_028 3 files changed +69
-0
lines changed Original file line number Diff line number Diff line change 17
17
| 21| [ Merge Two Sorted Lists] [ 021 ] | Linked List|
18
18
| 26| [ Remove Duplicates from Sorted Array] [ 026 ] | Array, Two Pointers|
19
19
| 27| [ Remove Element] [ 027 ] | Array, Two Pointers|
20
+ | 28| [ Remove Element] [ 028 ] | Array, Two Pointers|
20
21
21
22
22
23
## Medium
48
49
[ 021 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/021/README.md
49
50
[ 026 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/026/README.md
50
51
[ 027 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/027/README.md
52
+ [ 028 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/028/README.md
Original file line number Diff line number Diff line change
1
+ # [ Implement strStr()] [ title ]
2
+
3
+ ## Description
4
+
5
+ Implement strStr().
6
+
7
+ Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
8
+
9
+ ** Tags:** Two Pointers, String
10
+
11
+
12
+ ## 思路
13
+
14
+ 题意是从主串中找到子串的索引,如果找不到则返回-1,我们只需要遍历主串长度减字串长度即可,利用substring比较即可。
15
+
16
+ ``` java
17
+ public class Solution {
18
+ public int strStr (String haystack , String needle ) {
19
+ int l1 = haystack. length(), l2 = needle. length(), l3 = l1 - l2;
20
+ int l3 = l1 - l2;
21
+ for (int i = 0 ; i <= l3; ++ i) {
22
+ if (haystack. substring(i, i + l2). equals(needle)) {
23
+ return i;
24
+ }
25
+ }
26
+ return - 1 ;
27
+ }
28
+ }
29
+ ```
30
+
31
+
32
+ ## 结语
33
+
34
+ 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[ awesome-java-leetcode] [ ajl ]
35
+
36
+
37
+
38
+ [ title ] : https://leetcode.com/problems/implement-strstr
39
+ [ ajl ] : https://github.com/Blankj/awesome-java-leetcode
Original file line number Diff line number Diff line change
1
+ package com .blankj .easy ._028 ;
2
+
3
+ /**
4
+ * <pre>
5
+ * author: Blankj
6
+ * blog : http://blankj.com
7
+ * time : 2017/04/21
8
+ * desc :
9
+ * </pre>
10
+ */
11
+
12
+ public class Solution {
13
+ public int strStr (String haystack , String needle ) {
14
+ int l1 = haystack .length (), l2 = needle .length (), l3 = l1 - l2 ;
15
+ for (int i = 0 ; i <= l3 ; ++i ) {
16
+ if (haystack .substring (i , i + l2 ).equals (needle )) {
17
+ return i ;
18
+ }
19
+ }
20
+ return -1 ;
21
+ }
22
+
23
+ public static void main (String [] args ) {
24
+ Solution solution = new Solution ();
25
+ System .out .println (solution .strStr ("12345" , "23" ));
26
+ System .out .println (solution .strStr ("12345" , "" ));
27
+ }
28
+ }
You can’t perform that action at this time.
0 commit comments