题目如力扣剑指offer19
这道题的核心思路是判断模式串第二位是否是*,采用递归算法非常的好用
class Solution {
public boolean isMatch(String s, String p) {
if (s == null || p == null)
return false;
int strindex = 0;
int patindex = 0;
return matching(s, strindex, p, patindex);
}
//strindex和patindex用来作指针
public boolean matching(String string, int strindex, String pattern, int patindex) {
if (string.length() == strindex && pattern.length() == patindex)
return true;
if (string.length() != strindex && pattern.length() == patindex)
return false;
//如果第二位是*,可以选择匹配*前面的字符,也可以不匹配。
if (patindex + 1 < pattern.length() && pattern.charAt(patindex + 1) == '*') {
if (strindex != string.length()
&& (string.charAt(strindex) == pattern.charAt(patindex) || pattern.charAt(patindex ) == '.')) {
return matching(string, strindex, pattern, patindex + 2)
|| matching(string, strindex + 1, pattern, patindex);
}
else{
return matching(string, strindex, pattern, patindex + 2);
}
}
if (strindex != string.length()
&& (string.charAt(strindex) == pattern.charAt(patindex) || (pattern.charAt(patindex) == '.'))) {
return matching(string, strindex + 1, pattern, patindex + 1);
}
return false;
}
}