File tree Expand file tree Collapse file tree 3 files changed +55
-1
lines changed
【044】【Wildcard Matching】/src Expand file tree Collapse file tree 3 files changed +55
-1
lines changed Original file line number Diff line number Diff line change 1
1
# Created by .ignore support plugin (hsz.mobi)
2
2
* .iml
3
3
.idea
4
-
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @author: wangjunchao(王俊超)
3
+ * @time: 2018-09-28 15:25
4
+ **/
5
+ public class Solution {
6
+ public boolean isMatch (String str , String pattern ) {
7
+ // 匹配串的索引
8
+ int s = 0 ;
9
+ // 模式串的索引
10
+ int p = 0 ;
11
+ // 记录匹配的匹配位置
12
+ int match = 0 ;
13
+ // 星号的起始索引
14
+ int starIdx = -1 ;
15
+ while (s < str .length ()) {
16
+ // 两个指针都往前推进
17
+ if (p < pattern .length () && (pattern .charAt (p ) == '?' || str .charAt (s ) == pattern .charAt (p ))) {
18
+ s ++;
19
+ p ++;
20
+ }
21
+ // 发现一个*,只前进模式串索引
22
+ else if (p < pattern .length () && pattern .charAt (p ) == '*' ) {
23
+ // 记录最后一次发现*的位置
24
+ starIdx = p ;
25
+ // 记录在匹配串中匹配*时的位置
26
+ match = s ;
27
+ // 模式串索引向前推进
28
+ p ++;
29
+ }
30
+ // last pattern pointer was *, advancing string pointer
31
+ // 最后的模式串索引是*,匹配串索引向前推进。这个条件隐含p >= pattern.length(),再加上starIdx != -1
32
+ // 说明存在*号匹配,在星号匹配的
33
+ else if (starIdx != -1 ) {
34
+ // 记录模式串最后处理的*号的下一个位置
35
+ p = starIdx + 1 ;
36
+ // 记录在匹配串中匹配*时的位置
37
+ match ++;
38
+ // 匹配串索引向前推进
39
+ s = match ;
40
+ }
41
+ // 当前的模式索引指向的不是*号,最后一个模式索引指向的也不是*号,说明不匹配
42
+ else {
43
+ return false ;
44
+ }
45
+ }
46
+
47
+ // 检查余下的模式串,模式串必须全都是*号才行
48
+ while (p < pattern .length () && pattern .charAt (p ) == '*' ) {
49
+ p ++;
50
+ }
51
+
52
+ return p == pattern .length ();
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments