Skip to content

Commit d0ea246

Browse files
committed
pattern
1 parent 7b55bdb commit d0ea246

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package backtracking;
2+
3+
4+
public class Pattern {
5+
public static void main(String[] args) {
6+
Pattern obj = new Pattern("*aa?b".toCharArray(), 5);
7+
boolean result = obj.match("bbaabbc".toCharArray(), 7);
8+
boolean result1 = obj.match("bbaabb".toCharArray(), 6);
9+
System.out.println("bbaabbc match *aa?b > " + result);
10+
System.out.println("bbaabb match *aa?b > " + result1);
11+
}
12+
13+
private boolean matched = false;
14+
private char[] pattern; // 正则表达式
15+
private int plen; // 正则表达式长度
16+
17+
public Pattern(char[] pattern, int plen) {
18+
this.pattern = pattern;
19+
this.plen = plen;
20+
}
21+
22+
public boolean match(char[] text, int tlen) { // 文本串及长度
23+
matched = false;
24+
rmatch(0, 0, text, tlen);
25+
return matched;
26+
}
27+
28+
private void rmatch(int ti, int pj, char[] text, int tlen) {
29+
if (matched) return; // 如果已经匹配了,就不要继续递归了
30+
if (pj == plen) { // 正则表达式到结尾了
31+
if (ti == tlen) matched = true; // 文本串也到结尾了
32+
return;
33+
}
34+
if (pattern[pj] == '*') { // *匹配任意个字符
35+
for (int k = 0; k <= tlen-ti; ++k) {
36+
rmatch(ti+k, pj+1, text, tlen);
37+
}
38+
} else if (pattern[pj] == '?') { // ?匹配0个或者1个字符
39+
rmatch(ti, pj+1, text, tlen);
40+
rmatch(ti+1, pj+1, text, tlen);
41+
} else if (ti < tlen && pattern[pj] == text[ti]) { // 纯字符匹配才行
42+
rmatch(ti+1, pj+1, text, tlen);
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)