- 题目:给定两个字符串,s为待匹配字符串,p为模式字符串
- 匹配规则: ‘?’能匹配任何单个字符,’*’能匹配任何字符序列包括空字符null
- 难度:Hard
- 思路:一开始思路方向是有的,但是分情况讨论没有理清楚,最后忍不住看了discuss,在源码上稍微优化了一下
- 代码:
public class Solution {
public boolean isMatch(String s, String p) {
int len1 = 0;
int len2 = 0;
int starIndex = -1;
int match = 0;
while(len1 < s.length()){
if(len2 < p.length() && (p.charAt(len2) == '?' || (s.charAt(len1) != '*' &&s.charAt(len1) == p.charAt(len2)))){
len1++;
len2++;
}else if(len2 < p.length() && p.charAt(len2) == '*'){
starIndex = len2;
match = len1;
len2++;
}else if(starIndex != -1){
len2 = starIndex + 1;
match++;
len1 = match;
}else{
return false;
}
}
while(len2 < p.length() && p.charAt(len2) == '*'){
len2++;
}
return len2 == p.length();
}
}