【leetcode-10】——Regular Expression Matching
题目
Given an input string (s) and a pattern §, 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 letters a-z. p could be
empty and contains only lowercase letters a-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 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 = “cab” 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 = “misisp*.” Output: false
使用动态规划解答
定义:dp[sl+1][pl+1]
当dp[i][j] 为ture时表示s从0-i与p从0-j匹配
当dp[i][j] 为false时表示s从0-i与p从0-j不匹配
初始值
(1)dp[0][0]=true
表示 零串与零模式串匹配
(2)dp[i][0]=false
表示 非零串与零模式串不匹配
(3)dp[0][j] 表示零串与非零模式串的匹配情况
dp[0][1]=false;
如果p的第j个字符串不为"*",那么一定不匹配,则 dp[0][j]=false;
如果p的第j个字符串为"*" ,dp[0][j] = dp[0][j - 2]
1. 如果s.charAt(i-1) == p.charAt(j-1)
那么dp[i][j] = dp[i - 1][j - 1];
2. 如果p.charAt(j-1)== '.'
那么dp[i][j] = dp[i - 1][j - 1];
3. 如果p.charAt(j-1) == '*'
3.1 如果当前字符与模式串的前一个字符相同或者模式串的前一个字符为.
那么 dp[i][j] = dp[i][j - 1] || dp[i - 1][j]|| dp[i][j - 2];
3.2 否则 dp[i][j] = dp[i][j - 2];
public class Solution10 {
public static boolean isMatch(String s, String p) {
int sl=s.length();
int pl=p.length();
boolean dp[][]=new boolean[sl+1][pl+1];
//初始化
dp[0][0]=true;
//初始化首列
for(int i = 1; i <= sl; i++){
dp[i][0] = false;
}
// 初始化首行
for(int j = 1; j <= pl; j++){
if(j == 1 || p.charAt(j-1) != '*')
dp[0][j] = false;
else dp[0][j] = dp[0][j - 2];
}
for(int i = 1; i <= sl; i++){
for(int j = 1; j <= pl; j++){
if(s.charAt(i-1) == p.charAt(j-1) ||p.charAt(j-1)== '.'){
dp[i][j] = dp[i - 1][j - 1];
}
else if(p.charAt(j-1) == '*'){
if(s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == '.'){
dp[i][j] = dp[i][j - 1] || dp[i - 1][j]|| dp[i][j - 2];
}
else{
dp[i][j] = dp[i][j - 2];
}
}
}
}
return dp[sl][pl];
}
public static void main(String[] args) {
String s = "aab",p = "c*a*b";
boolean f=Solution10.isMatch(s, p);
System.out.print(f);
}
}