File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments