Skip to content

Commit 40579a3

Browse files
author
王俊超
committed
commit
1 parent c3e974f commit 40579a3

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
# Created by .ignore support plugin (hsz.mobi)
22
*.iml
33
.idea
4-

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
}

0 commit comments

Comments
 (0)