Skip to content

Commit 2d69006

Browse files
authored
Merge pull request gzc426#21 from Mrkirito/master
2018.11.24 主线任务
2 parents efe6f98 + 9ca9912 commit 2d69006

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

2019.11.24/kiritocly

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.zhongan;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* @author chenliyang
7+
* @description 实现strStr()函数
8+
* @date 2018/11/24
9+
*/
10+
public class Leetcode28 {
11+
public static void main(String[] args) {
12+
Scanner sc = new Scanner(System.in);
13+
String haystack = sc.next();
14+
String needle = sc.next();
15+
System.out.println(strStr(haystack, needle));
16+
}
17+
18+
private static int strStr(String haystack, String needle) {
19+
if (needle.length() == 0) {
20+
//如果needle为空字符串则返回0
21+
return 0;
22+
}
23+
char[] haystackCharArray = haystack.toCharArray();
24+
char[] needleCharArray = needle.toCharArray();
25+
for (int i = 0; i < haystackCharArray.length; i++) {
26+
//遍历haystack,找到needle中的第一个字符在haystack中出现的位置的下标
27+
if (haystackCharArray[i] == needleCharArray[0]) {
28+
//比较needle中其他的字符是否与haystack对应位置匹配
29+
int index = i + 1;
30+
int j;
31+
for (j = 1; index < haystackCharArray.length && j < needleCharArray.length; j++) {
32+
if (haystackCharArray[index] == needleCharArray[j]) {
33+
//字符串中字符匹配则比较下一个字符
34+
index++;
35+
} else {
36+
break;
37+
}
38+
}
39+
if (j == needleCharArray.length) {
40+
//字符串全部匹配则返回needle字符串第一个字符在haystack中出现位置的下标
41+
return i;
42+
}
43+
}
44+
}
45+
//未匹配则返回-1
46+
return -1;
47+
}
48+
}

0 commit comments

Comments
 (0)