File tree Expand file tree Collapse file tree 1 file changed +110
-0
lines changed Expand file tree Collapse file tree 1 file changed +110
-0
lines changed Original file line number Diff line number Diff line change
1
+ ``` java
2
+ package sy181124 ;
3
+
4
+ /*
5
+ * 判断一个字符串在另一个字符串中出现的位置。如果不匹配就返回-1。
6
+ */
7
+ public class leetcode28 实现indexof_KMP
8
+ {
9
+
10
+ public static void main (String [] args )
11
+ {
12
+ System . out. println(index(" asdf12" , " 12" ));
13
+ System . out. println(KMP (" bnghd12sd34" , " ghd1" ));
14
+
15
+ }
16
+
17
+ /**
18
+ * 暴力解法
19
+ * @param a
20
+ * @param b
21
+ * @return
22
+ */
23
+ public static int index (String a ,String b )
24
+ {
25
+ if (a== null || b== null || a. length()< b. length())
26
+ return - 1 ;
27
+ if (b. length()== 0 )
28
+ return 0 ;
29
+ for (int i= 0 ;i< a. length();i++ )
30
+ {
31
+ if (i+ b. length()> a. length())
32
+ return - 1 ;
33
+
34
+ int index= i;
35
+ int j= 0 ;
36
+ for ( j= 0 ;j< b. length();j++ )
37
+ {
38
+ if (b. charAt(j)== a. charAt(index))
39
+ index++ ;
40
+ else
41
+ break ;
42
+ }
43
+ if (j== b. length())
44
+ return i;
45
+
46
+ }
47
+ return - 1 ;
48
+
49
+ }
50
+
51
+ /**
52
+ * KMP
53
+ * @param a
54
+ * @param b
55
+ * @return
56
+ */
57
+ public static int KMP (String a ,String b )
58
+ {
59
+ if (a== null || b== null || a. length()< b. length())
60
+ return - 1 ;
61
+ if (b. length()== 0 )
62
+ return 0 ;
63
+ char [] str1= a. toCharArray();
64
+ char [] str2= b. toCharArray();
65
+ int i1= 0 ;
66
+ int i2= 0 ;
67
+ int [] next= getNext(str2);
68
+
69
+ while (i1< str1. length && i2< str2. length)
70
+ {
71
+ if (str1[i1]== str2[i2])
72
+ {
73
+ i1++ ;
74
+ i2++ ;
75
+
76
+ }
77
+ else if (next[i2]== - 1 ) {
78
+ i1++ ;
79
+ }
80
+ else {
81
+ i2= next[i2];
82
+ }
83
+ }
84
+ return i2== str2. length? i1- i2: - 1 ;
85
+ }
86
+
87
+ private static int [] getNext (char [] str2 )
88
+ {
89
+ if (str2. length== 1 )
90
+ return new int []{- 1 };
91
+ int [] next= new int [str2. length];
92
+ next[0 ]= - 1 ;
93
+ next[1 ]= 0 ;
94
+ int i= 2 ;
95
+ int cn= 0 ;
96
+ while (i< next. length)
97
+ {
98
+ if (str2[i- 1 ]== str2[cn])
99
+ next[i++ ]= ++ cn;
100
+ else if (cn> 0 ) {
101
+ cn= next[cn];
102
+ }
103
+ else
104
+ next[i++ ]= 0 ;
105
+ }
106
+ return next;
107
+ }
108
+
109
+ }
110
+ ```
You can’t perform that action at this time.
0 commit comments