Implement wildcard pattern matching with support for
'?' and '*'.'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
如果s字符的i位和p字符的j位置如果想吻合则拿i+1 和j+1继续比较
用一个star来记录*出现的位置, 首先当前字符i先和*的下一位比较, 如果不符合的话, 那么用i+1和*下一位比较 以此类推
while循环以第一个字符的长度作为限定, 最后判定第一个字符循环完是否第二个字符也全部走完 走完true 否则false
public class Solution {
public boolean isMatch(String s, String p) {
int i = 0;
int j = 0;
int star = -1;
int mark = -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) == '*') {
star = j;
mark = i;
j++;
} else if (star != -1) {
//匹配s中当前字符与p中*后面的字符,如果匹配,则在第一个if中处理,如果不匹配,则继续比较s中的下一个字符。
j = star + 1;
i = mark + 1;
mark++;
} else {
return false;
}
}
while (j < p.length() && p.charAt(j) == '*') {//如果字符串后面有多余的*
j++;
}
return j == p.length();
}
}
没有评论:
发表评论