-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathStringMatch.java
More file actions
68 lines (54 loc) · 1.86 KB
/
Copy pathStringMatch.java
File metadata and controls
68 lines (54 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package stringMatch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StringMatch {
private int[] skip;
private int p;
private String str;
private String key;
public StringMatch(String key) {
skip = new int[256];
this.key = key;
for(int k = 0; k <= 255; k++)
skip[k] = key.length();
for(int k = 0; k < key.length() - 1; k++)
skip[key.charAt(k)] = key.length() - k - 1;
}
public void search(String str) {
this.str = str;
p = search(key.length()-1, str, key);
}
private int search(int p, String input, String key) {
while(p < input.length()) {
String tmp = input.substring(
p-key.length()+1, p+1);
if(tmp.equals(key)) // 比較兩字串是否相同
return p-key.length()+1;
p += skip[input.charAt(p)];
}
return -1;
}
public boolean hasNext() {
return (p != -1);
}
public String next() {
String tmp = str.substring(p);
p = search(p+key.length()+1, str, key);
return tmp;
}
public static void main(String[] args) throws IOException {
BufferedReader bufReader =
new BufferedReader(
new InputStreamReader(System.in));
System.out.print("請輸入字串:");
String str = bufReader.readLine();
System.out.print("請輸入搜尋關鍵字:");
String key = bufReader.readLine();
StringMatch strMatch = new StringMatch(key);
strMatch.search(str);
while(strMatch.hasNext()) {
System.out.println(strMatch.next());
}
}
}