Skip to content

Commit 3901d1d

Browse files
committed
实现 strStr() 函数。
1 parent c899c15 commit 3901d1d

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.algorithm.study.demo.algorithm.leetcode;
2+
3+
/**
4+
* 实现 strStr() 函数。
5+
*
6+
* 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。
7+
*
8+
* 示例 1:
9+
*
10+
* 输入: haystack = "hello", needle = "ll"
11+
* 输出: 2
12+
*
13+
* 来源:力扣(LeetCode)
14+
* 链接:https://leetcode-cn.com/problems/implement-strstr
15+
*/
16+
public class Solution12 {
17+
public static int strStr(String haystack, String needle) {
18+
int len=haystack.length();
19+
int n=needle.length();
20+
if (n>len){
21+
return -1;
22+
}
23+
if (len==n && haystack.equals(needle)){
24+
return 0;
25+
}
26+
for (int i=0;i<len-n+1;i++){
27+
if (haystack.substring(i,i+n).equals(needle)){
28+
return i;
29+
}
30+
}
31+
return -1;
32+
33+
}
34+
public static void main(String[] args) {
35+
System.out.println(strStr("abc","bc"));
36+
}
37+
}

0 commit comments

Comments
 (0)