题目地址:
中文:https://leetcode-cn.com/problems/regular-expression-matching/
英文:https://leetcode.com/problems/regular-expression-matching/
题目描述:
Given an input string s and a pattern p, implement regular expression matching with support for ‘.’ and ‘*’ where:
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
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 preceding 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
Constraints:
0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, ‘.’, and ‘*’.
It is guaranteed for each appearance of the character ‘*’, there will be a previous valid character to match.
思路:
有点像编译原理里的一个知识点,我忘了是啥了。。
这题在处理过程中对’.‘的处理是简单的,对’*'有点麻烦,因为※能匹配0到任意长度的前序元素。就会出现样例4中的情况,稍微有点麻烦。
其余就没啥了,按各种情况处理即可,注意s和p有可能为空串。
使用递归判断实现,具体看题解里的代码注释。
使用循环的话不知道可不可以,因为循环很难判断一些情况,比如字符串是“aaa”,模式是“a*a”的情况。就是一些出现※的地方,可能需要跳过,可能需要匹配,匹配的话也不一定全部匹配,比如刚才的例子,a※匹配两个a,而不是三个,所以写成循环可能要倒退指针,是很麻烦的。就是因为※可以代表0到多个,造成了这里判断的复杂性。
题解:
public static boolean isMatch(String s,String p){
//如果模式串匹配完了,字符串还没有完,说明匹配不成功,否则就是成功的
if(p.isEmpty()) return s.isEmpty();
boolean first_match = (!s.isEmpty()&&
(p.charAt(0)==s.charAt(0)||p.charAt(0)=='.'));
//如果出现有*的地方,就要对它进行匹配
//对出现*的地方匹配有两种方式
//1.是可以直接跳过
//2.是可以对其进行匹配,然后继续匹配字符串s
//注意1和2之间的关系是或,只要有一个能匹配下去,就可以成功
if(p.length()>=2 && p.charAt(1)=='*'){
return (isMatch(s,p.substring(2))||
(first_match && isMatch(s.substring(1),p)));
}else{
//如果没出现*,那就简单了,继续匹配就可以了
return first_match && isMatch(s.substring(1),p.substring(1));
}
}