Skip to content

Commit a6b4d46

Browse files
zhouboyi1998zhouboyi
authored andcommitted
docs(note): 添加题解:28. 找出字符串中第一个匹配项的下标
1 parent c17fd17 commit a6b4d46

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<h1 style="text-align: center;"> <span style="color: #00AF9B;">28. 找出字符串中第一个匹配项的下标</span> </h1>
2+
3+
### 🚀 LeetCode
4+
5+
<base target="_blank">
6+
7+
<span style="color: #00AF9B;">**Easy**</span> [**https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/**](https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/)
8+
9+
---
10+
11+
### ❓ Description
12+
13+
<br/>
14+
15+
给你两个字符串 `haystack``needle`
16+
17+
请你在 `haystack` 字符串中找出 `needle` 字符串的第一个匹配项的下标(下标从 `0` 开始)。
18+
19+
如果 `needle` 不是 `haystack` 的一部分,则返回 `-1`
20+
21+
<br/>
22+
23+
**示例 1:**
24+
25+
```
26+
输入: haystack = "sadbutsad", needle = "sad"
27+
输出: 0
28+
解释: "sad" 在下标 0 和 6 处匹配, 第一个匹配项的下标是 0, 所以返回 0
29+
```
30+
31+
**示例 2:**
32+
33+
```
34+
输入: haystack = "leetcode", needle = "leeto"
35+
输出: -1
36+
解释: "leeto" 没有在 "leetcode" 中出现, 所以返回 -1
37+
```
38+
39+
<br/>
40+
41+
**提示:**
42+
43+
* `1 <= haystack.length, needle.length <= 10^4`
44+
* `haystack``needle` 仅由小写英文字符组成
45+
46+
---
47+
48+
### ❗ Solution
49+
50+
<br/>
51+
52+
#### Java
53+
54+
```
55+
class Solution {
56+
public int strStr(String haystack, String needle) {
57+
int length1 = haystack.length();
58+
int length2 = needle.length();
59+
for (int i = 0; i < length1 - length2 + 1; i++) {
60+
int length = 0;
61+
for (int j = 0; j < length2; j++) {
62+
if (haystack.charAt(i + j) == needle.charAt(j)) {
63+
length++;
64+
} else {
65+
break;
66+
}
67+
}
68+
if (length == length2) {
69+
return i;
70+
}
71+
}
72+
return -1;
73+
}
74+
}
75+
```

markdown/hello/0000.Hello.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
| <span style="color: #FFB822;">**Medium**</span> | [**0024.两两交换链表中的节点**](../medium/0024.两两交换链表中的节点.md) |
2121
| <span style="color: #00AF9B;">**Easy**</span> | [**0026.删除有序数组中的重复项**](../easy/0026.删除有序数组中的重复项.md) |
2222
| <span style="color: #00AF9B;">**Easy**</span> | [**0027.移除元素**](../easy/0027.移除元素.md) |
23+
| <span style="color: #00AF9B;">**Easy**</span> | [**0028.找出字符串中第一个匹配项的下标**](../easy/0028.找出字符串中第一个匹配项的下标.md) |
2324
| <span style="color: #00AF9B;">**Easy**</span> | [**0035.搜索插入位置**](../easy/0035.搜索插入位置.md) |
2425
| <span style="color: #FF2D55;">**Hard**</span> | [**0041.缺失的第一个正数**](../hard/0041.缺失的第一个正数.md) |
2526
| <span style="color: #FF2D55;">**Hard**</span> | [**0042.接雨水**](../hard/0042.接雨水.md) |

0 commit comments

Comments
 (0)