Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character. '*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
-
s
could be empty and contains only lowercase lettersa-z
. -
p
could be empty and contains only lowercase lettersa-z
, and characters like.
or*
.
Example 1:
Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab" p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input: s = "aab" p = "c*a*b" Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
Example 5:
Input: s = "mississippi" p = "mis*is*p*." Output: false
根据题意分析 就是自己实现正则判断,对于输入的字符串s和正则字符串p进行校验:
(.*代表所有任意字符串 肯定为true)
首先判断 第一个字符是否相等 boolean firstMatch = (s.charAt(0) == p.charAt(0) )||(p.charAt(0) =='.')
题意中s只能为小写字母 p只能为小写字母或是 . (表示任意字母)或 *(表示0或n个前置值)
然后对s的第二个字符串进行判断
其中如果p的第二个字符串为* 则 第一个字符串匹配且递归判断 s.substring(1) 和正则 p 或 递归判断 s与正则 p.substring(2)
当p的第二个字母非*时 递归判断 s.substring(1)和p.substring(1)
注意判断各种特殊情况 即可完成
public boolean isMatch(String s, String p) {
if (p.isEmpty() && s.isEmpty()) {
return true;
}else if (p.isEmpty()) {
return false;
}
boolean firstMatch = (!s.isEmpty() && s.charAt(0) == p.charAt(0)) || p.charAt(0) == '.';
if (s.length() > 1) {
if (p.length() > 1) {
if (p.charAt(1) == '*') {
return (firstMatch && isMatch(s.substring(1), p)) || (p.length() > 2 && isMatch(s, p.substring(2)));
} else {
return firstMatch && isMatch(s.substring(1), p.substring(1));
}
} else {
return false;
}
} else if (s.length() == 1) {
if (p.length() == 1) {
return firstMatch;
}
if (p.length() > 1) {
if (p.charAt(1) == '*') {
return (firstMatch && isMatch("", p)) || (p.length() > 2 && isMatch(s, p.substring(2)));
} else {
return firstMatch && isMatch("", p.substring(1));
}
}
}else if(s.isEmpty()) {
if(p.length()>1 && p.charAt(1)=='*') {
if(p.length() >2) {
return isMatch("",p.substring(2));
}else {
return true;
}
}
}
return false;
}
最后结果有点惨呀。。。。