The idea is for ?., update both index; for *, record the position of star in p, and s, update p index, and keep s… until not equal, update p to be next to star position, and update s position by one, and use this new position. each time update s position, but star in p position will never change.
public class Solution {
public boolean isMatch(String s, String p) {
if(s == null || p == null){
if(s == null && p == null)
return true;
return false;
}
int i = 0;
int j = 0;
int recordStar = -1;
int recordPattern = -1;
while(i < s.length()){
if(j < p.length() && (p.charAt(j) == s.charAt(i) || p.charAt(j) == '?')){
i++;
j++;
} else if(j < p.length() && p.charAt(j) == '*'){
recordPattern = j;
recordStar = i;
j++;
} else if(recordPattern != -1){
j = recordPattern + 1; //never change
i = ++recordStar; //update each time
if(j >= p.length()) return true;
} else{
return false;
}
}
while(j < p.length()){
if(p.charAt(j) != '*'){
return false;
}
j++;
}
return true;
}
}
没有评论:
发表评论